1. 程式人生 > >病茶幾 例題

病茶幾 例題

查詢 div ret http cstring father init for include

技術分享

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #define F(i,s,e) for(int i=s;i<=e;i++)
 5 #define D(i,e,s) for(int i=e;i>=s;i--)
 6 using namespace std;
 7 int n,m,p,a,b;
 8 int father[5010];
 9 
10 int getfather(int x)
11 {
12     int y=x;
13     while(father[y]!=y)//查詢祖節點
14 y=father[y]; 15 while(x!=y)//更新路徑至父節點 16 { 17 int temp=father[x]; 18 father[x]=y; 19 x=temp; 20 } 21 return y; 22 } 23 24 bool check(int xx,int yy) 25 { 26 if(getfather(xx)==getfather(yy)) 27 return true; 28 else return false; 29 } 30 31
void init() 32 { 33 scanf("%d%d%d",&n,&m,&p); 34 F(i,1,n) 35 father[i]=i; 36 F(i,1,m) 37 { 38 scanf("%d%d",&a,&b); 39 int aa=getfather(a); 40 int bb=getfather(b); 41 if(aa!=bb) 42 father[aa]=bb; 43 } 44 F(i,1
,p) 45 { 46 scanf("%d%d",&a,&b); 47 if(check(a,b)) 48 puts("Yes"); 49 else puts("No"); 50 } 51 } 52 53 int main() 54 { 55 init(); 56 return 0; 57 }

病茶幾 例題