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

来源:互联网 发布:解压缩包的软件 编辑:程序博客网 时间:2024/04/19 22:57

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
22 11 2
output
1
input
22 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);    }}



0 0