8.9日总结

发布时间 2023-08-10 18:39:49作者: 许七安gyg

今天学习了并查集的知识,一般用于合并鞍和查询元素是否在集合里

模板

int p[x];//p[x]是x的祖宗节点

int find(int x)//find函数是用来找祖宗节点的(运用了路径压缩:将每个节点都指向根节点)
{
    if(p[x]!=x) p[x]=find(p[x]);
    return p[x];
}

例题


#include<iostream>
using namespace std;
const int N=1e5+10;
int n,m;
int p[N];
int find(int x)
{
    if(p[x]!=x) p[x]=find[p[x]];//路径压缩,将每个节点都指向根节点
    reuturn p[x]
}

int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++) p[i]=i;
    while(m--)
    {
        char op[2];
        int a,b;
        scanf("%s%d%d",op,&a,&b);
        if(op[0]=='M') p[find(a)]=find(b);
        else {
          if(find(a)==find(b)) cout<<"Yes"<<endl;
          else cout<<"No"<<endl;  
        }
            
    }
}