病茶几 例题

Posted on 2017-11-01 20:33  Murs  阅读(117)  评论(0)    收藏  举报

 

 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 }