Calabash is the servant of a landlord. The landlord owns a piece of land, which can be regarded as an infinite 2D plane. One day the landlord set up two orthogonal rectangular-shaped fences on his land. He asked Calabash a simple problem: how many nonempty connected components is my land divided into by these two fences, both finite and infinite? Calabash couldn't answer this simple question. Please help him! Recall that a connected component is a maximal set of points not occupied by the fences, and every two points in the set are reachable without crossing the fence.
Input
The first line of input consists of a single integer T (1≤T≤10000), the number of test cases. Each test case contains two lines, specifying the two rectangles. Each line contains four integers x1,y1,x2,y2 (0≤x1,y1,x2,y2≤109,x1<x2,y1<y2), where (x1,y1),(x2,y2) are the Cartesian coordinates of two opposite vertices of the rectangular fence. The edges of the rectangles are parallel to the coordinate axes. The edges of the two rectangles may intersect, overlap, or even coincide.
Output
For each test case, print the answer as an integer in one line.
Sample Input
3 0 0 1 1 2 2 3 4 1 0 3 2 0 1 2 3 0 0 1 1 0 0 1 1
Sample Output
3 4 2
题意:现在有两个长方形,给出了长方形的对角线的两个点的坐标,然后问你这两个长方形把整个区域划分成了几个部分。
这道题在当时比赛的时候想着是到简单题,事实证明确实是简单题,然而我们在一直分类讨论时候发现讨论情况越来越多,然而讨论的思路当时不是很清晰,于是就没做出来,看了题解以后来补一下这题。
题解:因为点数很少,把这些点进行离散化,之后进行搜索判断联通块即可,每个联通块就是一个区域,访问过之后打上标记,可以说也挺好想,就是当时没想到,直接上代码:
#include<bits/stdc++.h> using namespace std; int x[100],y[100],xx[100],yy[100],cnt=0; int mp[100][100]; int dx[4]={0,0,-1,1},dy[4]={1,-1,0,0}; void bfs(int x,int y){ mp[x][y]=1; queue<int> q; while(!q.empty())q.pop(); q.push(x); q.push(y); while(!q.empty()){ int xd=q.front();q.pop(); int yd=q.front();q.pop(); for(int i=0;i<4;i++){ int tx=xd+dx[i]; int ty=yd+dy[i]; if(mp[tx][ty]==0&&tx>=0&&ty>=0&&tx<=10&&ty<=10){ mp[tx][ty]=1; q.push(tx); q.push(ty); } } } } int main() { int t; scanf("%d",&t); while(t--){ cnt=0; memset(mp,0,sizeof(mp)); for(int i=0;i<4;i++){ scanf("%d%d",&x[i],&y[i]); xx[i]=x[i]; yy[i]=y[i]; } sort(xx,xx+4); sort(yy,yy+4); int len1=unique(xx,xx+4)-xx; int len2=unique(yy,yy+4)-yy; for(int i=0;i<4;i++){ x[i]=lower_bound(xx,xx+4,x[i])-xx; x[i]=x[i]*2+1; y[i]=lower_bound(yy,yy+4,y[i])-yy; y[i]=y[i]*2+1; } for(int i=x[0];i<=x[1];i++){ mp[i][y[0]]=1; mp[i][y[1]]=1; } for(int i=x[2];i<=x[3];i++){ mp[i][y[2]]=1; mp[i][y[3]]=1; } for(int i=y[0];i<=y[1];i++){ mp[x[0]][i]=1; mp[x[1]][i]=1; } for(int i=y[2];i<=y[3];i++){ mp[x[2]][i]=1; mp[x[3]][i]=1; } for(int i=0;i<10;i++){ for(int j=1;j<10;j++){ if(mp[i][j]==0){ cnt++; bfs(i,j); } } } cout<<cnt<<endl; } return 0; }