題目描述若某個家族人員過於龐大,要判斷兩個是否是親戚,確實還很不容易,現在給出某個親戚關係圖,求任意給出的兩個人是否具有親戚關係。 規定:x和y是親戚,y和z是親戚,那麼x和z也是親戚。 如果x,y是親戚,那麼x的親戚都是y的親戚,y的親戚也都是x的親戚。 輸入格式第一行:三個整數n,m,p,(n<=5000,m<=5000,p<=5000),分別表示有n個人,m個親戚關係,詢問p對親戚關係。 以下m行:每行兩個數Mi,Mj,1<=Mi,Mj<=N,表示Ai和Bi具有親戚關係。接下來p行:每行兩個數Pi,Pj,詢問Pi和Pj是否具有親戚關係。輸出格式P行,每行一個'Yes'或'No'。表示第i個詢問的答案為“具有”或“不具有”親戚關係。
Sample Input6 5 31 21 53 45 21 31 42 35 6
SampleOutputYesYesNo
#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <ctime>#include <cmath>#define mxn 5000+10#define locusing namespace std;int n,m,p;int f[mxn];int fd(int x){ if (f[x]==x) return x; f[x]=fd(f[x]); return f[x];}int mrg(int x,int y){ int rx=fd(x),ry=fd(y); f[rx]=f[ry];}int main(){ #ifdef loc freopen("family.in","r",stdin); freopen("family.out","w",stdout); #endif scanf("%d%d%d",&n,&m,&p); for (int i=1;i<=n;++i) f[i]=i; int x,y; for (int i=1;i<=m;++i) { scanf("%d%d",&x,&y); mrg(x,y); } for (int i=1;i<=p;++i) { scanf("%d%d",&x,&y); if (fd(x)==fd(y)) printf("Yes\n"); else printf("No\n"); } return 0;}