poj2528 Mayor's posters (线段树+离散化)

恩,这区间范围挺大的,需要离散化。如果TLE,还需要优化一下常数。

AC代码

#include <stdio.h>
#include <string.h>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
const int maxn = 40000+5;
typedef pair<int, int> Pii;
Pii a[10000 + 5];
int b[maxn], vis[10000+5], c[maxn];

int setv[maxn << 2];

void buildTree(int o, int l, int r) {
    setv[o] = -1;
    if(l < r) {
        int m = (l+r) / 2;
        buildTree(o*2, l, m);
        buildTree(o*2+1, m+1, r);
    }
}

void pushDown(int o) {
    int lc = o*2, rc = o*2+1;
    if(setv[o] != -1) {
        setv[lc] = setv[rc] = setv[o];
    }
    setv[o] = -1;
}

int ul, ur;
void update(int o, int l, int r, int v) {
    if(ul <= l && r <= ur) {
        setv[o] = v;
    } else {
        pushDown(o);
        int m = (l+r) / 2;
        if(ul <= m)
            update(o*2, l, m, v);
        if(m < ur)
            update(o*2+1, m+1, r, v);
    }
}

void query(int o) {
    if(setv[o] != -1) {
        vis[setv[o]] = 1;
        return;
    }
    query(o*2);
    query(o*2+1);
}

int main() {
    int T, n;
    scanf("%d", &T);
    while(T--) {
        scanf("%d", &n);
        for(int i = 0; i < n; i++) {
            scanf("%d%d", &a[i].first, &a[i].second);
            b[i*2] = a[i].first;
            b[i*2+1] = a[i].second;
        }
        sort(b, b+2*n);
        int cnt = 0;
        c[0] = b[0];
        cnt = 1;
        for(int i = 1; i < 2*n; i++) {
            if(b[i] == b[i-1]) continue;
            if(b[i] - b[i-1] > 1) 
                c[cnt++] = b[i-1] + 1;
            c[cnt++] = b[i];
        }
        buildTree(1, 1, cnt);
        for(int i = 0; i < n; i++) {
            ul = lower_bound(c, c+cnt, a[i].first) - c + 1;
            ur = lower_bound(c, c+cnt, a[i].second) - c + 1;
            update(1, 1, cnt, i);
        }
        memset(vis, 0, sizeof(vis));
        query(1);
        int ans = 0;
        for(int i = 0; i < n; i++) {
            ans += vis[i];
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

posted @ 2018-04-17 08:28  flyawayl  阅读(186)  评论(0编辑  收藏  举报