POJ 2528 Mayor's posters 离散化+线段树+简单Hash

题意:在墙上贴海报,海报可以互相覆盖,问最后可以看见几张海报
思路:这题数据范围很大,直接搞超时+超内存,需要离散化:
离散化简单的来说就是只取我们需要的值来用,比如说区间[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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章