坐标离散化

来源:互联网 发布:知网查重入口 知乎 编辑:程序博客网 时间:2024/06/09 17:37

W*h的格子上画了n条或垂直或水平的宽度为1的直线,求这些直线将格子划分成了多少个区域?

 

输入

第一行三个整数w,h,n

接下来的4行为依次为x1,x2,y1,y2

1<=w,h<=1e6

1<=n<=500

 

输出

单独一行即区域的个数

 

样例

Input

10 10 5

1 1 4 9 10

6 10 4 9 10

4 8 1 1 6

4 8 10 5 10

 

Output

6

 

思路

准备好w*h的数组,利用dfs或bfs求联通块的个数的方法可以求解,但是这里的w和h太大了,空间不够,所以要用到坐标离散化的技巧,即将前后没有变化的行列消除后并不会影响区域的个数,所以数组里存储有直线的行列和它左右或上下的行列就足够了,空间大小不会超过6n*6n,再利用bfs求解联通块的数量(dfs可能会栈溢出)即可。

 

代码

 

#include<queue>#include<cstdio>#include<vector>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef pair<int, int> p;const int maxn = 550;const int dx[4] = { 0, 1, 0, -1 };const int dy[4] = { 1, 0, -1, 0 };int w, h, n;int X1[maxn], X2[maxn], Y1[maxn], Y2[maxn];bool fld[6 * maxn][6 * maxn];int compress(int *x1, int *x2, int w) {//坐标离散化函数vector<int> xs;for (int i = 0; i < n; i++) {for (int d = -1; d <= 1; d++) {int tx1 = x1[i] + d;int tx2 = x2[i] + d;if (tx1 > 0 && tx1 <= w) xs.push_back(tx1);if (tx2 > 0 && tx2 <= w) xs.push_back(tx2);}}sort(xs.begin(), xs.end());xs.erase(unique(xs.begin(), xs.end()), xs.end());//经典的去重操作for (int i = 0; i < n; i++) {x1[i] = find(xs.begin(), xs.end(), x1[i]) - xs.begin();x2[i] = find(xs.begin(), xs.end(), x2[i]) - xs.begin();}return xs.size();}void bfs() {//用宽度优先搜索求联通块数量memset(fld, 0, sizeof(fld));for (int i = 0; i < n; i++) {for (int y = Y1[i]; y <= Y2[i]; y++)for (int x = X1[i]; x <= X2[i]; x++)fld[y][x] = 1;//注意y是行,x是列}int ans = 0;for (int y = 0; y < h; y++) {for (int x = 0; x < w; x++) {if (fld[y][x]) continue;ans++;queue<p> que;que.push(p(y, x));while (!que.empty()) {int y0 = que.front().first;int x0 = que.front().second;fld[y0][x0] = 1;que.pop();for (int k = 0; k < 4; k++) {int y = dy[k] + y0;int x = dx[k] + x0;if (y < 0 || y >= h || x < 0 || x >= w) continue;if (fld[y][x]) continue;que.push(p(y, x));}}}}printf("%d\n", ans);}int main() {while (scanf("%d%d%d", &w, &h, &n) == 3) {for (int i = 0; i < n; i++) scanf("%d", &X1[i]);for (int i = 0; i < n; i++) scanf("%d", &X2[i]);for (int i = 0; i < n; i++) scanf("%d", &Y1[i]);for (int i = 0; i < n; i++) scanf("%d", &Y2[i]);w = compress(X1, X2, w);h = compress(Y1, Y2, h);bfs();}return 0;}

原创粉丝点击