L2-1 分而治之

思路

这题的意思是,如果把这些点打掉,其他的点是否能够完全不连通。

用并查集,或者打上标记之后,判断每个点是否还能到达其他点,如果一个点可以到达其他任何点,都应该输出否。

代码

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e4+10;
int x[maxn],y[maxn],pre[maxn];

void init(int n) {
    for (int i=1;i<=n;i++) {
        pre[i]=i;
    }
}

int getBlock(int n){
    int res=0;
    for (int i=1;i<=n;i++) {
        if (pre[i]==i) {
            res++;
        }
    }
    return res;
}

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

void unions(int x,int y) {
    int fx=find(x);
    int fy=find(y);
    if (fx!=fy) {
        pre[fx]=fy;
    }
}
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for (int i=0;i<m;i++) {
        scanf("%d%d",&x[i],&y[i]);
    }
    int k,p,tmp;
    scanf("%d",&k);
    while (k--) {
        unordered_map<int,int> cache;
        scanf("%d",&p);
        while (p--) {
            scanf("%d",&tmp);
            cache[tmp]=1;
        }
        init(n);
        for (int i=0;i<n;i++) {
            if (!(cache[x[i]]||cache[y[i]])) {
                unions(x[i],y[i]);
            }
        }
        int ans=getBlock(n);
        if (ans==n) {
            printf("YES\n");
        }
        else {
            printf("NO\n");
        }
    }
    return 0;
}

原文链接: https://www.cnblogs.com/xyqxyq/p/12337441.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    L2-1 分而治之

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/330762

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午5:43
下一篇 2023年3月1日 下午5:45

相关推荐