并查集模板

牛客测试链接:https://www.nowcoder.com/practice/e7ed657974934a30b2010046536a5372
小挂大+路径压缩

#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
typedef long long ll;
int father[N];
int sz[N];
int stk[N];
int n,m;

void init()
{
    for(int i=0;i<n;i++)
    {
        father[i]=i;
        sz[i]=1;
    }
}

int find(int x)
{
    int size=0;
    while(x!=father[x])
    {
        stk[size++]=x;
        x = father[x];
    }
    while(size>0)
    {
        father[stk[--size]]=x;
    }
    return x;
}


bool issameset(int a,int b)
{

    return find(a)==find(b);
}

void connect(int x,int y)
{
    int fx = find(x);
    int fy = find(y);
    if(fx!=fy)
    {
        if(sz[fx]>=sz[fy])
        {
            sz[fx]+=sz[fy];
            father[fy] = fx;
        }
        else
        {
            sz[fy]+=sz[fx];
            father[fx]=fy;
        }
    }
    
}


int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    init();
    for(int i=0;i<m;i++)
    {
        int opt,x,y;
        cin>>opt>>x>>y;
        if(opt==1)
        {
            if(issameset(x,y))cout<<"Yes"<<endl;
            else cout<<"No"<<endl;
        }
        else 
        {
            connect(x,y);
        }
    }


    return 0;
}

精简版+路劲压缩

#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
typedef long long ll;
int father[N];
int n,m;

void init()
{
    for(int i=0;i<n;i++)father[i]=i;
}

int find(int x)
{
    return x==father[x]?x:father[x]=find(father[x]);
}


bool issameset(int a,int b)
{

    return find(a)==find(b);
}

void connect(int x,int y)
{

    father[find(x)]=find(y);
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    init();
    for(int i=0;i<m;i++)
    {
        int opt,x,y;
        cin>>opt>>x>>y;
        if(opt==2)
        {
            if(issameset(x,y))cout<<"Y"<<endl;
            else cout<<"N"<<endl;
        }
        else 
        {
            connect(x,y);
        }
    }

    return 0;
}
posted @ 2025-07-11 11:40  屈臣  阅读(9)  评论(0)    收藏  举报