您的位置:首页 > 其它

并查集Codeforces Round #134 (Div. 1), problem: (A) Ice Skating

2015-05-11 09:40 465 查看
A. Ice Skating

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get
from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.

We assume that Bajtek can only heap up snow drifts at integer coordinates.

Input

The first line of input contains a single integer n (1 ≤ n ≤ 100)
— the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000)
— the coordinates of the i-th snow drift.

Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis.
All snow drift's locations are distinct.

Output

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

Sample test(s)

input
2
2 1
1 2


output
1


input
2
2 14 1


output
0


题意:一个人初学滑雪,他只会上下左右沿直线滑雪,下面有n个坐标,给出这些休息地点,同一行或者同一列的话,他就可以滑过去休息,但是可能还会有一些地点他滑不过去问至少还要再建几个休息的地点,他才可以全部滑到.

分析:这个题目就是典型的并查集了,判断两个点在同一行或者同一列就可以连在一起,最后看有几个根节点就好了

下面贴出代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int father[105];
struct point{
int x,y;
}p[105];
void init(){
int i;
for(i=0;i<105;i++)
father[i]=i;
}
int find_father(int x){
return x==father[x]?x:father[x]=find_father(father[x]);
}
void union_tree(int x,int y){
father[find_father(x)]=father[find_father(y)];
}
int main(void){
int i,j,n,m,cnt;
while(scanf("%d",&n)!=EOF){
init();
cnt=0;
for(i=0;i<n;i++)
scanf("%d %d",&p[i].x,&p[i].y);
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(p[j].x==p[i].x||p[i].y==p[j].y){
union_tree(i,j);
}
}
}
for(i=0;i<n;i++)
if(father[i]==i)
cnt++;
printf("%d\n",cnt-1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: