並查集

題目描述ios

輸入格式ide

第一行:三個整數n,m,p,(n<=5000,m<=5000,p<=5000),分別表示有n我的,m個親戚關係,詢問p對親戚關係。spa

如下m行:每行兩個數Mi,Mj,1<=Mi,Mj<=N,表示Ai和Bi具備親戚關係。code

接下來p行:每行兩個數Pi,Pj,詢問Pi和Pj是否具備親戚關係。遞歸

輸出格式ci

P行,每行一個’Yes’或’No’。表示第i個詢問的答案爲「具備」或「不具備」親戚關係。
樣例輸入:
6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6
樣例輸出:
Yes
Yes
Noget

解題思路:先進行初始化每一個元素的祖宗節點爲-1,而後根據親戚關係進行合併,查找祖先節點的時候要注意終止條件,這裏的終止條件爲-1.it

//並查集 
//1.初始化
//2.查找
//3.合併 
#include<iostream>
using namespace std;
int n,m,p;
int pre[5050]; 
//初始化 
void init()
{
    for(int i = 1; i <= n; i++){
        pre[i] = -1;    //pre[i]表明i的父節點 
    }
}
//查找集合i的源頭(遞歸實現) 
int find(int i){
    if(pre[i] == -1)   //若是集合i的父親是-1,說明本身就是源頭,返回本身(一顆樹向上回溯查找,直到源頭) 
    return i;
    return find(pre[i]);
}
void gets(int a,int b){
    int x = find(a);  //查找a的源頭   
    int y = find(b);
    if(x != y){     // 若是a和b的源頭不相同,則合併 
    pre[y] = x; 
}
}
int main(){
    cin>>n>>m>>p;
    init();
    int a,b;
    for(int i = 1; i <= m; i++){
        cin>>a>>b;
        gets(a,b);
    }
    for(int i = 1; i <= p; i++){
        cin>>a>>b;
        if(find(a) != find(b)){
            cout<<"No"<<endl;
        }
        else
            cout<<"Yes"<<endl;
    }
    return 0;
}
相關文章
相關標籤/搜索