思路
模拟 + 双指针
用pair类型的数组将连续天数存下来 –>
sort()排序(按first升序) –>
处理交叉的连续天数(双指针l, r) –>
用s[N]将所有的连续区间之间的相隔天数记录下来(补签卡多了) –>
模拟l -> nn(处理后的连续区间数), res接受以l为首区间的最大连续天数
#include <iostream>
#include <cstring>
#include <algorithm>
#define LL long long //int
#define x first
#define y second
using namespace std;
const int N = 1e5 + 10;
typedef pair<LL, LL> PLL;
LL n, m;
PLL q[2 * N];
LL s[N];
int main()
{
while(cin >> n >> m)
{
for(int i = 0; i < n; i ++ )
{
LL l, r;
cin >> l >> r;
q[i] = PLL(l, r);
}
sort(q, q + n);
int nn = 0;
for(int l = 0, r = l + 1; l < n; l ++ )
{
LL fin = q[l].y;
while(fin >= q[r].x && r < n)
fin = max(fin, q[r].y), r ++ ;
r -- ;
q[nn ++ ] = PLL(q[l].x, fin);
l = r;
}
for(int i = 1; i < nn; i ++ )
s[i] = s[i - 1] + q[i].x - q[i - 1].y - 1;
LL res = 0;
for(int l = 0, r = 0; l < nn && r < nn; l ++ )
{
while(s[r] - s[l] <= m && r < nn)
r ++ ;
r -- ;
res = max(res, q[r].y - q[l].x + 1 + m - (s[r] - s[l]));
}
cout << res << endl;
}
return 0;
}