codevs 1073 家族 并查集

题目链接:

http://www.codevs.cn/problem/1073/

题意:

题解:

代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 #define MS(a) memset(a,0,sizeof(a))
 5 #define MP make_pair
 6 #define PB push_back
 7 const int INF = 0x3f3f3f3f;
 8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
 9 inline ll read(){
10     ll x=0,f=1;char ch=getchar();
11     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
12     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
13     return x*f;
14 }
15 //////////////////////////////////////////////////////////////////////////
16 const int maxn = 5e3+10;
17 
18 int fa[maxn];
19 
20 int find(int x){
21     return fa[x]==x ? x : fa[x]=find(fa[x]);
22 }
23 
24 void Union(int u,int v){
25     int t1 = find(u), t2 = find(v);
26     if(t1 == t2)
27         return ;
28     else
29         fa[t1] = t2;
30 }
31 
32 int main(){
33     int n,m,q;
34     scanf("%d%d%d",&n,&m,&q);
35     for(int i=0; i<maxn; i++)
36         fa[i] = i;
37     while(m--){
38         int u,v; scanf("%d%d",&u,&v);
39         Union(u,v);
40     }
41     while(q--){
42         int u,v;
43         scanf("%d%d",&u,&v);
44         if(find(u) == find(v))
45             puts("Yes");
46         else
47             puts("No");
48     }
49 
50     return 0;
51 }
原文地址:https://www.cnblogs.com/yxg123123/p/6827650.html