天梯练习L2-025-分而治之(典型的并查集)

题目连接L2-025-分而治之

#include<bits/stdc++.h>
using namespace std;
const int N=1e4+5;
struct node{
    int x,y;
}edge[N];

int del[N];
int f[N];

int find(int x){
    if(f[x]==x)return x;
    return f[x]=find(f[x]);
}

void unionxy(int a,int b){
    int x=find(a);
    int y=find(b);
    if(x!=y){
        f[x]=y;
    }
}
int main(){
    int n,m;
    cin>>n>>m;
    
    for(int i=0;i<m;i++){
        int x,y;
        cin>>x>>y;
        edge[i].x=x;
        edge[i].y=y;
    }
    int k;
    cin>>k;
    
    for(int i=0;i<k;i++){
        for(int t=1;t<=n;t++){
            f[t]=t;
        }
        memset(del,0,sizeof(del));
        int np;
        cin>>np;
        for(int j=0;j<np;j++){//先把所有的要攻打的城市标记好
            int x;
            cin>>x;
            del[x]=1;
        }
        for(int j=0;j<m;j++){//并查集求出有多少个”部落“
            if(del[edge[j].x]!=1&&del[edge[j].y]!=1){
                unionxy(edge[j].x,edge[j].y);
            }
        }
        int cnt=0;
        for(int j=1;j<=n;j++){
            if(f[j]==j)cnt++;
        }
        // cout<<cnt<<endl;
        if(cnt==n)cout<<"YES"<<endl;//“部落”数等于所有城市数,说明一个城市就是一个部落
        else cout<<"NO"<<endl;
    }
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值