题目可以理解为:给定一个大区间,每次用不同种颜色覆盖一段区间,问最后这个大区间上有几种颜色。
由于区间很大,所以先要对数据进行离散化,考虑到最后覆盖的区间一定在上方,所以倒着做,从最后一段覆盖上的区间开始往前,一开始大区间为空,随着区间被覆盖,如果这次覆盖的区间没有覆盖到新的空区间,从倒序的意义上来说,这段区间就被遮盖掉了,否则的话就多一种颜色。每段连续的已被覆盖的区间用一个并查集维护,时间复杂度为O(n),排序的时间为O(nlogn),总的复杂度为O(nlogn)。
#include
#include
#include
#include
#include
#include
using namespace std; const int maxn = 10005; int father[maxn << 2]; bool vis[maxn << 2]; int n, Case, Right, ans; bool expose; int *dis[maxn << 1]; struct Que {int left, right;}; Que C[maxn]; int cmp(int *a, int *b) { return *a < *b; } int find(int temp) { if (temp >= Right) return father[temp]; if (vis[temp]) father[temp] = find(father[temp]); else { vis[temp] = true; expose = true; father[temp] = find(father[temp + 1]); } return father[temp]; } int main() { scanf("%d", &Case); while (Case--) { memset(vis, false, sizeof(vis)); scanf("%d", &n); for (int i = 0; i < n * 3; i++) father[i] = i; int count = 0; for (int i = 0; i < n; i++) { scanf("%d", &C[i].left); dis[count] = &C[i].left; count++; scanf("%d", &C[i].right); C[i].right++; dis[count] = &C[i].right; count++; } sort(dis, dis + count, cmp); int cnt = 0, save; save = *dis[0]; *dis[0] = 0; for (int i = 1; i < count; i++) { if(save != *dis[i]) cnt++; save = *dis[i]; *dis[i] = cnt; } ans = 0; for (int i = n - 1; i >= 0; i--) { Right = C[i].right; expose = false; find(C[i].left); if (expose)ans++; } printf("%d\n", ans); } }