考虑如果是一条链怎么做。
其实很简单,按照左端点排序,贪心地能选就选即可。
原题是环,那么断环成链即可。
发现每一次暴力跳会 TLE,于是考虑用倍增优化。
设 (f_{i,j}) 表示从第 (i) 个区间开始选 (2^j) 个区间最远覆盖到哪里。
转移直接倍增即可。
注意算答案时要加上首尾两个区间。
#include <bits/stdc++.h>
#define DEBUG fprintf(stderr, "Passing [%s] line %d
", __FUNCTION__, __LINE__)
#define File(x) freopen(x".in","r",stdin); freopen(x".out","w",stdout)
using namespace std;
typedef long long LL;
typedef pair <int, int> PII;
typedef pair <int, PII> PIII;
template <typename T>
inline T gi()
{
T f = 1, x = 0; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return f * x;
}
const int INF = 0x3f3f3f3f, N = 200003, M = N << 1;
int n, m;
int f[23][M];
int tot, ans[N];
struct Node {int l, r, id;} a[M];
inline bool cmp(Node x, Node y) {return x.l < y.l;}
int main()
{
// File("");
n = gi <int> (), m = gi <int> ();
for (int i = 1; i <= n; i+=1)
{
int l = gi <int> (), r = gi <int> ();
if (l <= r) a[++tot] = {l, r, i}, a[++tot] = {l + m, r + m, i + n};
else a[++tot] = {l, r + m, i}, a[++tot] = {l + m, m + m, i + n};
}
sort(a + 1, a + 1 + tot, cmp);
int now = 1;
for (int i = 1; i <= tot; i+=1)
{
while (now < tot && a[now + 1].l <= a[i].r) ++now;
f[0][i] = now;
}
for (int j = 1; j <= 21; j+=1)
for (int i = 1; i <= tot; i+=1)
f[j][i] = f[j - 1][f[j - 1][i]];
for (int i = 1; i <= n; i+=1)
{
int res = 2, now = i;
for (int j = 21; j >= 0; j-=1)
if (f[j][now] && a[f[j][now]].r < a[i].l + m)
res += (1ll << j), now = f[j][now];
ans[a[i].id] = res;
}
for (int i = 1; i <= n; i+=1) printf("%d ", ans[i]);
return 0;
}