[算法设计与分析] 亲戚 (并查集)
tag:并查集
1 // 2 // main.cpp 3 // 亲戚 4 // 5 // Created by sylvia on 2021/10/31. 6 // Copyright © 2021 apple. All rights reserved. 7 // 8 //并查集板子题 9 #include <iostream> 10 #include <stdio.h> 11 #include <math.h> 12 #include <algorithm> 13 #include <string.h> 14 using namespace std; 15 #define M 5000+5 16 #define N 10000+5 17 struct edge{ 18 int u,v; 19 }a[N]; 20 21 int V,E; //顶点数与边数 22 int father[M],rankk[M]; 23 void init(int n){//并查集初始化 24 for (int i=0;i<n;i++){ 25 father[i]=i; 26 rankk[i]=0; 27 } 28 } 29 int find(int x){ 30 int j,k,r; 31 r=x; 32 while (r!=father[r]) r=father[r]; 33 k=x; 34 while (k!=r){ 35 j=father[k]; 36 father[k]=r; 37 k=j; 38 } 39 return r; 40 } 41 void unite(int x,int y){ //合并集合 42 x=find(x); 43 y=find(y); 44 if(x==y) return; 45 if (rankk[x]<rankk[y]) father[x]=y; 46 else { 47 father[y]=x; 48 if(rankk[x]==rankk[y]) rankk[x]++; 49 } 50 } 51 int same(int x,int y){ //判断是否在一个集合 52 return find(x)==find(y); 53 } 54 55 56 int main(){ 57 int p; 58 int x,y; 59 cin>>V>>E>>p; 60 init(V); 61 62 for (int i=0;i<E;i++){ 63 cin>>a[i].u>>a[i].v; 64 if(!same(a[i].u-1,a[i].v-1)){ 65 unite(a[i].u-1,a[i].v-1); 66 } 67 } 68 while (p--){ 69 cin>>x>>y; 70 if (same(x-1,y-1)) cout<<"Yes"<<endl; 71 else cout<<"No"<<endl; 72 } 73 74 return 0; 75 }