我是靠谱客的博主 曾经河马,这篇文章主要介绍CodeForces 217 A.Ice Skating(并查集),现在分享给大家,希望可以做个参考。

Description
给出n个点的横纵坐标,两个点互通当且仅当两个点有相同的横坐标或纵坐标,问最少需要加几个点才能使得所有点都两两互通
Input
第一行一个整数n表示点数,之后n行每行两个整数x[i]和y[i]表示第i个点的横纵坐标(1<=n<=100,1<=x[i],y[i]<=1000)
Output
输出需要加的最少点数
Sample Input
2
2 1
1 2
Sample Output
1
Solution
并查集,先把横坐标或纵坐标相同的点合并,最后得到num个集合,两个集合之间只需要一个点就可以联系起来,所以要加的点数就是num-1个
Code

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<cmath> #include<vector> #include<queue> #include<map> #include<set> #include<ctime> using namespace std; typedef long long ll; #define INF 0x3f3f3f3f #define maxn 111 int n,x[maxn],y[maxn],fa[maxn]; void init() { for(int i=1;i<=n;i++)fa[i]=i; } int find(int x) { if(fa[x]==x)return x; return fa[x]=find(fa[x]); } void unite(int x,int y) { x=find(x),y=find(y); if(x==y)return ; fa[x]=y; } int main() { while(~scanf("%d",&n)) { init(); for(int i=1;i<=n;i++)scanf("%d%d",&x[i],&y[i]); for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) if(x[i]==x[j]||y[i]==y[j])unite(i,j); int ans=0; for(int i=1;i<=n;i++) if(fa[i]==i)ans++; printf("%dn",ans-1); } return 0; }

最后

以上就是曾经河马最近收集整理的关于CodeForces 217 A.Ice Skating(并查集)的全部内容,更多相关CodeForces内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部