宁波工程学院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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值