题意简述:
有 (n) 个闭区间,求最多选择多少个两两不交的区间,并输出最小字典序方案。
(1le nle 2 imes 10^5)。
第一问很好做,是经典贪心问题。直接按照右端点排序依次扫即可。
考虑第二问。由最小字典序,立刻想到按顺序插入。于是我们可以用一个 set 维护当前可用的区间,每次操作先删除包含于当前区间的可用区间,然后判断它两边的区间能放置的区间个数 (+1) 是否等于原来区间能放置的区间个数。
具体的,假设当前区间是 ([l,r]),包含于它的可用区间是 ([L,R]),那么我们就要判断是否存在 (cnt(L,l-1)+cnt(r+1,R)+1=cnt(L,R)),其中 (cnt(i,j)) 为区间 ([i,j]) 能放置的区间个数。
如何快速求解 (cnt(i,j))?一种很好的思路是倍增。设 (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)
#define DC int T = gi <int> (); while (T--)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
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;
struct Node {int id, l, r;} a[N], b[N];
int u[M], tot, cnt;
int f[M][23];
set <PII> s;
inline int Find(int x) {return lower_bound(u + 1, u + 1 + cnt, x) - u;}
inline void chkmin(int &x, int y) {if (y < x) x = y;}
inline bool bh(PII x, PII y) {return x.fi <= y.fi && x.se >= y.se;}
inline int query(PII x)
{
int u = x.fi, res = 0;
for (int i = 18; i >= 0; i-=1)
if (f[u][i] <= x.se) u = f[u][i], res += (1 << i);
return res;
}
int main()
{
// freopen(".in", "r", stdin); freopen(".out", "w", stdout);
n = gi <int> (); for (int i = 1; i <= n; i+=1) a[i].l = u[++tot] = gi <int> (), a[i].r = u[++tot] = gi <int> (), a[i].id = i;
sort(u + 1, u + 1 + tot); cnt = unique(u + 1, u + 1 + tot) - u - 1;
for (int i = 1; i <= n; i+=1) a[i].l = Find(a[i].l), a[i].r = Find(a[i].r), b[i] = a[i];
sort(a + 1, a + 1 + n, [](Node x, Node y) {return (x.r ^ y.r) ? (x.r < y.r) : (x.l < y.l);});
int cnt1 = 0, nowr = 0;
for (int i = 1; i <= n; i+=1) if (a[i].l > nowr) nowr = a[i].r, ++cnt1;
printf("%d
", cnt1);
memset(f, 0x3f, sizeof f);
for (int i = 1; i <= n; i+=1) chkmin(f[a[i].l][0], a[i].r);
for (int i = cnt; i >= 1; i-=1) chkmin(f[i][0], f[i + 1][0]);
for (int j = 1; j <= 18; j+=1)
for (int i = 1; i <= cnt; i+=1)
if (f[i][j - 1] != 0x3f3f3f3f) chkmin(f[i][j], f[f[i][j - 1] + 1][j - 1]);
s.insert({1, cnt});
for (int i = 1; i <= n; i+=1)
{
auto it = s.lower_bound({b[i].l, b[i].r}), it1 = --s.lower_bound({b[i].l, b[i].r});
PII tmp;
if (bh(*it, {b[i].l, b[i].r})) tmp = *it;
else if (bh(*it1, {b[i].l, b[i].r})) tmp = *it1;
else continue;
PII now1 = {tmp.fi, b[i].l - 1}, now2 = {b[i].r + 1, tmp.se};
int qwq = query({tmp.fi, tmp.se});
if (query(now1) + query(now2) + 1 >= qwq)
{
s.erase(s.find(tmp));
if (now1.fi <= now1.se) s.insert(now1);
if (now2.fi <= now2.se) s.insert(now2);
printf("%d ", i);
}
}
puts("");
return 0;
}