題意:在牆上貼海報,海報可以互相覆蓋,問最後可以看見幾張海報
思路:這題數據範圍很大,直接搞超時+超內存,需要離散化:
離散化簡單的來說就是隻取我們需要的值來用,比如說區間[1000,2000],[1990,2012]
我們用不到[-∞,999][1001,1989][1991,1999][2001,2011][2013,+∞]這些值,所以我只需要1000,1990,2000,2012就夠了,將其分別映射到0,1,2,3,在於複雜度就大大的降下來了
所以離散化要保存所有需要用到的值,排序後,分別映射到1~n,這樣複雜度就會小很多很多
而這題的難點在於每個數字其實表示的是一個單位長度(並且一個點),這樣普通的離散化會造成許多錯誤(包括我以前的代碼,poj這題數據奇弱)
給出下面兩個簡單的例子應該能體現普通離散化的缺陷:
1-10 1-4 5-10
1-10 1-4 6-10
爲了解決這種缺陷,我們可以在排序後的數組上加些處理,比如說[1,2,6,10]
如果相鄰數字間距大於1的話,在其中加上任意一個數字,比如加成[1,2,3,6,7,10],然後再做線段樹就好了.
線段樹功能:update:成段替換
query:簡單hash
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10000 + 10;
bool Hash[maxn];
int le[maxn], ri[maxn], x[maxn<<2];
int color[maxn<<4];//數組小心
int cnt;
void pushdown(int root){
if (color[root] != -1){ //被覆蓋了
color[root<<1] = color[root<<1|1] = color[root];
color[root] = -1;
}
}
void update(int root, int l, int r, int L, int R, int c){
if (L<=l && r<=R){
color[root] = c;
return;
}
pushdown(root);
int m = (l+r) >> 1;
if (L <= m) update(root<<1, l, m, L, R, c);
if (R > m) update(root<<1|1, m+1, r, L, R, c);
}
void query(int root, int l, int r){
if (color[root] != -1){
if (!Hash[color[root]]) cnt++; //簡單hash判重
Hash[color[root]] = true;
return;
}
if (l == r) return;
pushdown(root);
int m = (l+r) >> 1;
query(root<<1, l, m);
query(root<<1|1, m+1, r);
}
int BSearch(int key, int n){ //二分查找
int l = 0, r = n - 1;
while (l <= r){
int m = (l + r) >> 1;
if (x[m] == key) return m;
if (x[m] < key) l = m + 1;
else
r = m - 1;
}
return -1;
}
int main(){
int t;
scanf("%d", &t);
while (t--){
int n;
scanf("%d", &n);
int gnt = 0;
for (int i = 0; i<n; i++){
scanf("%d%d", &le[i], &ri[i]);
x[gnt++] = le[i];
x[gnt++] = ri[i];
}
sort(x, x+gnt);
int m = 1;
for (int i = 1; i<gnt; i++) // 去重
if (x[i] != x[i-1]) x[m++] = x[i];
for (int i = m-1; i>0; i--) //排除特殊情況
if (x[i] != x[i-1] + 1) x[m++] = x[i-1] + 1;
sort(x, x+m);
memset(color, -1, sizeof(color));
for (int i = 0; i<n; i++){
int l = BSearch(le[i], m);
int r = BSearch(ri[i], m);
update(1, 0, m-1, l, r, i);
}
cnt = 0;
memset(Hash, false, sizeof(Hash));
query(1, 0, m-1);
printf("%d\n", cnt);
}
return 0;
}