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

来源:互联网 发布:企业cms开源 编辑:程序博客网 时间:2024/06/16 15:03

题目链接:点击打开链接

题意:在墙上贴海报,海报可以相互重叠,问最后可以看到几张海报

思路:可以采用线段树,按照贴海报的顺序去更新线段树染色,最后查询整个区间的染色数即为所求;但是数据太大,而且我们只需要某个区间的左右范围和区间 的相对位置,不需要区间内具体数据,所以可以只用有用数据,进行离散化。

离散化简单的来说就是只取我们需要的值来用,复杂度就大大的降下来了。离散化要保存所有需要用到的值,排序后,分别映射到1~n,这样复杂度就会小很多很多
而这题的难点在于每个数字其实表示的是一个单位长度(并非一个点),这样普通的离散化会造成许多错误
给出下面两个简单的例子应该能体现普通离散化的缺陷:
例子一:1-10 1-4 5-10
例子二:1-10 1-4 6-10
普通离散化后都变成了[1,4][1,2][3,4],[1,4]覆盖了[1,2],[3,4],而例子二原始数据并没有覆盖,如果先更新[1,4],再更新[1,2],[3,4],就会出现问题,这段区间由应该三个颜色变为了两个颜色,为了解决这种缺陷,我们可以在排序后的数组上加些处理,比如说[1,2,6,10]
如果相邻数字间距大于1的话,在其中加上任意一个数字,比如加成[1,2,3,6,7,10],这样就避免了原始数据大小不相邻的数最后离散化后相邻,然后再做线段树就好了

// POJ 2528 Mayor's posters.cpp 运行/限制:79ms/1000ms#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace std;#define MAXN 10010#define lson l, m, root << 1#define rson m + 1, r, root << 1 | 1int cnt;int left[MAXN], right[MAXN], re[MAXN << 2], color[MAXN << 4];//一开始想错了,re开小了,re[MAXN * 3],RE了3次......bool book[MAXN];int binarySearch(int num, int l, int r, int a[]) {while (l <= r) {int m = (l + r) >> 1;if (num == a[m]) {return m;}else if (num < a[m]) {r = m - 1;}else {l = m + 1;}}return -1;}void pushDown(int root) {if (color [root] == -1) {return;}color[root << 1] = color[root << 1 | 1] = color[root];color[root] = -1;}void update(int le,int rig,int col,int l,int r,int root) {if (le <= l && rig >= r) {color[root] = col;return;}pushDown(root);int m = (l + r) >> 1;if (le <= m) {update(le, rig, col, lson);}if (rig > m) {update(le, rig, col, rson);}}void query(int l, int r, int root) {if (color[root] != -1) {if (book[color[root]] == false) {book[color[root]] = true;cnt++;}return;}if (l == r) {return;}int m = (l + r) >> 1;query(lson);query(rson);}int main(){int k, n;scanf("%d", &k);while (k--) {cnt = 0;memset(color, -1, sizeof(color));memset(book, false, sizeof(book));scanf("%d", &n);int m = 0;for (int i = 0; i < n; i++) {scanf("%d%d", &::left[i], &::right[i]);re[m++] = ::left[i];re[m++] = ::right[i];}//离散化sort(re, re + m);int w = 1;for (int i = 1; i < m; i++) {if (re[i] != re[i - 1]) {re[w++] = re[i];}}for (int i = w - 1; i > 0; i--) {if (re[i] - re[i - 1] != 1) {re[w++] = re[i - 1] + 1;}}sort(re, re + w);for (int i = 0; i < n; i++) {//查找离散化后对应的坐标int a = binarySearch(::left[i],0, w - 1, re);int b = binarySearch(::right[i], 0, w - 1, re);update(a, b, i, 0, w - 1, 1);//i为color,给画板涂色}query(0, w - 1, 1);printf("%d\n", cnt);}    return 0;}



原创粉丝点击