其他分享
首页 > 其他分享> > 【洛谷】P1551 亲戚(并查集)

【洛谷】P1551 亲戚(并查集)

作者:互联网

并查集裸题直接附上ac代码

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <queue>
#include <set>
#include <map>
#define dbg(a)  cout<<#a<<" : "<<a<<endl;
using namespace std;
typedef long long ll;
ll fa[200005];
ll rnk[200005];
ll find(ll x)
{
    //return x==fa[x]?x:(fa[x]=find(x));
    if(fa[x]==x)
        return x;
    else{
        fa[x]=find(fa[x]);  //父节点设为根节点
        return fa[x];   //返回父节点
    }
}
void merge(ll i,ll j)
{
    ll x=find(i);
    ll y=find(j);
    if(rnk[x]<=rnk[y]){
        fa[x]=y;
    }
    else{
        fa[y]=x;
    }
    if(x!=y && rnk[x]==rnk[y])
    {
        rnk[y]++;
    }
}
void init(ll n)
{
    for(ll i=1;i<=n;i++)
    {
        fa[i]=i;
        rnk[i]=1;
    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    ll n,m,p;
    cin>>n>>m>>p;
    ll x,y;
    init(n);
    for(ll i=1;i<=m;i++)
    {
        cin>>x>>y;
        merge(x,y);
    }
    for(ll i=1;i<=p;i++)
    {
        cin>>x>>y;
        if(find(x)==find(y))
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    }
    return 0;
}

 

标签:ac,洛谷,cout,ll,查集,P1551,include,find
来源: https://blog.csdn.net/weixin_45720782/article/details/116404191