数据结构——并查集

并查集是一种十分基础和有用的数据结构,网上有很多讲解的很好的博客,为了便于理解,建议刚接触的人可以将其理解成向量,一组连通的向量就是一个集合,假如要合并两个集合,也就是在两组无关联的向量中增加一条道路,为了方便,我们直接把其中某一组向量的头头直接指向另一组向量的头头。也就是合并操作了。

例题:

 

 

#include<iostream>
using namespace std;

const int N = 100010;

int p[N];
int n,m;

int find(int x){
    if(p[x]!=x){
        //路径压缩
        p[x] = find(p[x]);
    }
    return p[x];
}

void merge(int x,int y){
     p[find(x)] = find(y);
}

int main(){
    
    cin>>n>>m;
    for(int i = 0 ; i <= n ; i++) p[i] = i;
    char ch;
    int a,b;
    for(int i = 0 ; i < m ; i ++) {
        cin>>ch>>a>>b;    
        if(ch=='M'){
            merge(a,b);
        }
        if(ch=='Q'){
            if(find(a)==find(b)){
                puts("Yes");
            }else{
                puts("No");
            }
        }
        
    }
    
    
    return 0;
}

 

posted @ 2020-02-06 16:29  FLydoggie  阅读(138)  评论(0)    收藏  举报