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

来源:互联网 发布:linux samba 配置 编辑:程序博客网 时间:2024/04/30 13:48
/*这道题,真的做了很久,终于AC。①原来使用哈希判重,结果超时,其实一次历遍就行②在search()函数中,需要考虑查找成功和失败两种情况,失败情况容易忽略③其实对于“区间更新”问题,算法不存在错误,可以作为模版。至于A[l] ++ , A[r + 1] --,这个只能处理求和问题,实际对效率无太大影响,只是多一个log(n)④离散化处理的第一道问题,两重for()循环即可,一个判重、一个插入数据因为对于[1,10],[1,4],[5,10]和[1,10],[1,4],[6,10],两种情况,离散化后变为[1,4],[1,2],[3,4].这样的话[1,2],[3,4]会将[1,4]覆盖,对于第一种情况正确,第二种情况则会出错。处理方法,如果a1,a2离散化后相邻,a1>a2+1,则再插入a2+1即可*/#include <cstdio>#include <cstring>#include <cstdlib>const int nMax = 50007;//const int HASH = 12007;struct Lenth{int l, r;}lenth[nMax];struct Tree{int l, r;int color;Tree(){}Tree(int l, int r, int color):l(l), r(r), color(color){}}tree[nMax * 4];int A[nMax];int len;//int hash[HASH];int visit[nMax];int ans;int cmp(const void *a, const void *b){int *pa = (int *) a;int *pb = (int *) b;return *pa - *pb;}void build(int rt, int l, int r){if(l < r){int mid = (l + r) / 2;build(rt * 2, l, mid);build(rt * 2 + 1, mid + 1, r);}tree[rt] = Tree(l, r, -1);}void update(int rt, int l, int r, int color)//只需要在tree[rt].color>=0上进行处理,至于等于-2的情况,前面已经做过处理,所以不需要再次操作{if(A[tree[rt].l] == l && A[tree[rt].r] == r){tree[rt].color = color;}else{int mid = (tree[rt].l + tree[rt].r) / 2;if(tree[rt].color >= 0 && tree[rt].color != color){update(rt * 2, A[tree[rt].l], A[mid], tree[rt].color);update(rt * 2 + 1, A[mid + 1], A[tree[rt].r], tree[rt].color);}if(r <= A[mid])update(rt * 2, l, r, color);else if(A[mid + 1] <= l)update(rt * 2 + 1, l, r, color);else{update(rt * 2, l, A[mid], color);update(rt * 2 + 1, A[mid + 1], r, color);}tree[rt].color = -2;}}void search(int rt)//需要考虑搜索到最后但是没有找到的情况,否则会Runtime Error{if(tree[rt].color >= 0)//查找到{if(visit[tree[rt].color] == 0){visit[tree[rt].color] = 1;ans ++;}return;}else if(tree[rt].l == tree[rt].r)//未查找到return;else{search(rt * 2);search(rt * 2 + 1);}}int main(){//freopen("e://data.in", "r", stdin);int T;scanf("%d", &T);while(T --){int N;scanf("%d", &N);int i;len = 0;//memset(hash, -1, sizeof(hash));for(i = 0; i < N; ++ i){scanf("%d%d", &lenth[i].l, &lenth[i].r);//if(insert(lenth[i].l)) A[len ++] = lenth[i].l;//if(insert(lenth[i].r)) A[len ++] = lenth[i].r;}qsort(A, len, sizeof(A[0]), cmp);int m = 1;for(i = 1; i < len; ++ i){if(A[i] != A[i - 1])A[m ++] = A[i];}len = m;for(i = 1; i < len; ++ i){if(A[i] > A[i - 1] + 1)A[m ++] = A[i - 1] + 1;}len = m;qsort(A, len, sizeof(A[0]), cmp);build(1, 0, len - 1);//从0还是从1开始,其实无影响for(i = 0; i < N; ++ i){update(1, lenth[i].l, lenth[i].r, i);}memset(visit, 0, sizeof(visit));ans = 0;search(1);printf("%d\n", ans);}return 0;}

原创粉丝点击