[SSL] 1222 rectangle (combined search)
Time Limit:2000MS
Memory Limit:65536K
Description
There are n rectangles on a plane. The sides of each rectangle are parallel to the coordinate axis and have vertices whose values are integers. We define the block in the following way.
Each rectangle is a block.
If two different rectangles have common line segments, then they form a new block to cover their original two blocks.
Example:
The rectangle in Figure 1 forms two different blocks.
Write a program:
find the number of different blocks formed by these rectangles.
Input
In the first line of the input file PRO.IN, there is another integer n, 1 <= n <=7000, indicating the number of rectangles. The next n lines describe the vertices of the rectangle. Each rectangle is described by four numbers: the coordinates of the lower left vertex (x, y) and the coordinates of the upper right vertex (x, y). The coordinates of each rectangle are non-negative integers not exceeding 10,000.
Output
There should be only one integer in the first line of the file PRO.OUT—representing the number of different blocks composed of a given rectangle.
Sample Input
9
0 3 2 6
4 5 5 7
4 2 6 4
2 0 3 2
5 3 6 4
3 2 5 3
1 4 4 7
0 0 1 4
0 0 4 1
Sample Output
2
Ideas
Think of rectangles as points, and rectangles with common sides are connected to each other. Use Union to find.
Code
#include<iostream>
#include<cstdio>
using namespace std;
int n,m,p,f[7010],l[7010],r[7010],u[7010],d[7010];
int find(int x)//找代表值
{
if(x==f[x])return x;
return f[x]=find(f[x]);
}
void merge(int x,int y)//合并
{
return;
}
bool pd(int x,int y)//判矩形是否有公共边
{
if(d[x]>u[y]||d[y]>u[x]||l[x]>r[y]||l[y]>r[x])//完全不接触
return 0;
if((d[x]==u[y]&&l[x]==r[y])||(d[x]==u[y]&&l[y]==r[x])||(d[y]==u[x]&&l[x]==r[y])||(d[y]==u[x]&&l[y]==r[x]))//一个点接触
return 0;
return 1;
}
int main()
{
int i,j,x,y,ans;
scanf("%d",&n);
ans=n;
for(i=1;i<=n;f[i]=i,i++);
for(i=1;i<=n;i++)//合并
{
scanf("%d%d%d%d",&d[i],&l[i],&u[i],&r[i]);
for(j=1;j<i;j++)
if(find(i)!=find(j)&&pd(i,j))
f[find(j)]=find(i),ans--;//连边
}
printf("%d",ans);
return 0;
}