天天看點

CodeVS 1073家族(并查集)

CodeVS 1073家族☆

題目描述 Description 

若某個家族人員過于龐大,要判斷兩個是否是親戚,确實還很不容易,現在給出某個親戚關系圖,求任意給出的兩個人是否具有親戚關系。 規定:x和y是親戚,y和z是親戚,那麼x和z也是親戚。如果x,y是親戚,那麼x的親戚都是y的親戚,y的親戚也都是x的親戚。

輸入描述 Input Description 

第一行:三個整數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是否具有親戚關系。

輸出描述 Output Description 

P行,每行一個’Yes’或’No’。表示第i個詢問的答案為“具有”或“不具有”親戚關系。

樣例輸入 Sample Input 

6 5 3 

1 2 

1 5 

3 4 

5 2 

1 3 

1 4 

2 3 

5 6

樣例輸出 Sample Output 

Yes 

Yes 

No

資料範圍及提示 Data Size & Hint 

n<=5000,m<=5000,p<=5000

分析: 并查集模闆題,x和y是親戚,則把x、y所在的集合進行并集。查詢x和y是否是親戚,則查詢x和y是否在同一集合中。

//家族 并查集 
#include <cstdio>
using namespace std;
int f[5001], n, m, p;
int find(int x)
{
    if(f[x]==x)return x;
    else return f[x]=find(f[x]);
}
void input()
{
    int i, a, b;
    scanf("%d%d%d",&n,&m,&p);
    for(i=1;i<=n;i++)f[i]=i;
    for(i=1;i<=m;i++)
    {
        scanf("%d%d",&a,&b);
        f[find(b)]=find(a);
    }
}
void answer()
{
    int i, a, b;
    for(i=1;i<=p;i++)
    {
        scanf("%d%d",&a,&b);
        if(find(a)==find(b))printf("Yes\n");
        else printf("No\n");
    }
}
int main()
{
    input();
    answer();
    return 0;
}