您的位置:首页 > 其它

CF218C:Ice Skating(并查集)

2017-02-11 23:26 267 查看
C. 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.

Examples

input
2
2 1
1 2


output
1


input
2
2 14 1


output
0


思路:将行相同或列相同的点合并为一棵树,最后看有多少棵树即可计算还需多少个点。

# include <stdio.h>
int pre[101];
struct node
{
int x, y;
}a[101];

void init(int n)
{
for(int i=0; i<=n; ++i)
pre[i] = i;
}

int find(int x)
{
if(x != pre[x])
pre[x] = find(pre[x]);
return pre[x];
}

int main()
{
int n;
while(~scanf("%d",&n))
{
init(n);
int ans = 0;
for(int i=0; i<n; ++i)
scanf("%d%d",&a[i].x, &a[i].y);
for(int i=0; i<n; ++i)
for(int j=i+1; j<n; ++j)
{
if(a[i].x==a[j].x || a[i].y == a[j].y)
{
int px = find(i);
int py = find(j);
if(px != py)
{
++ans;
pre[py] = px;
}
}
}
printf("%d\n",n-1-ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: