寧波工程學院2020新生校賽 L 小梁的道館(並查集)

添加鏈接描述
題目描述
小梁變強之後決定建設自己的道館,她特別喜歡去其他的道館串門。
但是有些道館之間沒有道路連通,於是小梁想知道自己能不能去她想去的道館,
你能幫她寫一個程序來查詢兩個道館之間是否互相存在道路聯通嗎;
如果存在輸出“YES”,反之輸出“NO”。
輸入描述:
第一行爲三個整數N爲道館個數,M爲線路條數,T爲查詢次數(1≤N<1000,1≤M<1000,1≤T<10000)第二行至第M+1行,每行兩個整數,代表兩個道館的編號a,b(1≤a≤1000,1≤b≤1000),表示這兩個道館之間有道路相連
第M+2行至第M T+2M+T+2行,每行兩個整數,代表查詢這兩個道館。

輸出描述:
T行,每行對應一個查詢,假如查詢的道館之間可以連接則輸出YES,否則則輸出NO。
示例1
輸入

4 2 2
1 3
4 3
1 2
3 4

輸出

NO
YES

並查集裸題。沒啥說的。

#include<bits/stdc++.h>
#include<bitset>
#include<unordered_map>
#define pb push_back
#define bp __builtin_popcount
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e6+100;
const int MOD=1e9+7;
int lowbit(int x){return x&-x;}
inline ll dpow(ll a, ll b){ ll r = 1, t = a; while (b){ if (b & 1)r = (r*t) % MOD; b >>= 1; t = (t*t) % MOD; }return r; }
inline ll fpow(ll a, ll b){ ll r = 1, t = a; while (b){ if (b & 1)r = (r*t); b >>= 1; t = (t*t); }return r; }
int pre[maxn];
int unionserch(int root)
{

    int son,temp;
    son=root;

    while(root!=pre[root])
    {

        root=pre[root];
    }
    while(son!=root)
    {

        temp=pre[son];
        pre[son]=root;
        son=temp;
    }
    return root;
}
int main()
{
    int n,m,t;
    cin>>n>>m>>t;
    for(int i=1;i<=n;i++)
    pre[i]=i;

    for(int i=1;i<=m;i++)
    {
        int x,y;
        cin>>x>>y;
        int bx=unionserch(x);
        int by=unionserch(y);
        if(bx!=by)
        pre[bx]=by;
    }

    for(int i=1;i<=t;i++)
    {
        int x,y;
        cin>>x>>y;
        int bx=unionserch(x);
        int by=unionserch(y);
        if(bx==by)cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章