题意:
给 n 个海报,顺序贴上去,后贴的海报会覆盖之前的海报,问最后能看见的海报种类数。
题解:
最近把线段树又看了一遍,感觉对线段树的理解加深了一些。(之前连理解都有问题,还是太菜了TAT)
这道题显然暴力去更新是会超时的,那么可以想到用线段树来解决,之前也做过一个类似的数颜色,这道题有所不同的是数据量太大,但是海报数量却并不多,所以可以离散化处理。
然而普通的离散化是行不通的,例如:
1 10
1 3
6 10
如果普通离散化会变成:
1 4
1 2
3 4
这样的话答案就是 2 了,但是显然答案是 3。
所以这时就得在离散化的时候处理一下,也就是如果两个数之间差不为 1 ,那么就在这两个数之间插入一个数字,这样就解决了这个问题。
代码:
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<bitset>
#define INF 0x3f3f3f3f
#define MAXM 5 + 10
#define MAXN 40000 + 10
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
int t, n;
struct node{
int l, r;
}no[MAXN];
int a[MAXN<<2];
int tree[MAXN<<3];
int vis[MAXN<<2];
void push(int rt)
{
if(tree[rt] != -1){
tree[rt<<1] = tree[rt];
tree[rt<<1|1] = tree[rt];
tree[rt] = -1;
}
}
void update(int l, int r, int c, int L, int R, int rt)
{
if(l <= L && R <= r){
tree[rt] = c;
return ;
}
push(rt);
int mid = (L + R) / 2;
if(l <= mid)
update(l, r, c, L, mid, rt << 1);
if(r > mid)
update(l, r, c, mid + 1, R, rt << 1 | 1);
}
void query(int l, int r, int L, int R, int rt)
{
if(tree[rt] != -1){
vis[tree[rt]] = 1;
return ;
}
push(rt);
int mid = (L + R) / 2;
if(l <= mid)
query(l, r, L, mid, rt << 1);
if(r > mid)
query(l, r, mid + 1, R, rt << 1 | 1);
}
void init()
{
memset(tree, -1, sizeof(tree));
memset(a, 0, sizeof(a));
memset(no, 0, sizeof(no));
memset(vis, 0, sizeof(vis));
}
int main()
{
scanf("%d", &t);
while(t --){
init();
scanf("%d", &n);
int cnt = 0;
for(int i = 0; i < n; i ++){
scanf("%d %d", &no[i].l, &no[i].r);
a[cnt++] = no[i].l; a[cnt++] = no[i].r;
}
sort(a, a + cnt);
cnt = unique(a, a + cnt) - a;
int temp = cnt;
for(int i = 0; i < temp - 1; i ++){
if(a[i] != a[i+1] - 1)
a[cnt++] = a[i] + 1;
}
sort(a, a + cnt);
cnt = unique(a, a + cnt) - a;
for(int i = 0; i < n; i ++){
int l = no[i].l, r = no[i].r;
l = lower_bound(a, a + cnt, l) - a + 1;
r = lower_bound(a, a + cnt, r) - a + 1;
update(l, r, i, 1, cnt, 1);
}
query(1, cnt, 1, cnt, 1);
int ans = 0;
for(int i = 0; i < n; i ++)
if(vis[i])
ans ++;
printf("%d\n", ans);
}
}
/*
The WAM is F**KING interesting .
*/