【洛谷】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;
}

 

上一篇:[ERR] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ……


下一篇:洛谷-P1551 亲戚