BZOJ1116:[POI2008]CLO

浅谈并查集:https://www.cnblogs.com/AKMer/p/10360090.html

题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=1116

树是\(NIE\),基环树是\(TAK\),任意有环的图都可以通过删边变成基环树。

所以用并查集判判每个联通块是否有环即可。

时间复杂度:\(O(\alpha{n})\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
using namespace std;
 
const int maxn=1e5+5;
 
int n,m;
int fa[maxn];
bool cir[maxn];
 
int read() {
    int x=0,f=1;char ch=getchar();
    for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
    for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
    return x*f;
}
 
int find(int x) {
    if(fa[x]==x)return x;
    return fa[x]=find(fa[x]);
}
 
int main() {
    n=read(),m=read();
    for(int i=1;i<=n;i++)fa[i]=i;
    for(int i=1;i<=m;i++) {
        int a=read(),b=read();
        int p=find(a),q=find(b);
        if(p==q)cir[p]=1;
        if(cir[p])fa[q]=p;
        else fa[p]=q;
    }
    bool ans=1;
    for(int i=1;i<=n;i++)
        if(!cir[find(i)])ans=0;
    if(ans)puts("TAK");
    else puts("NIE");
    return 0;
}
posted @ 2019-02-13 09:40  AKMer  阅读(112)  评论(0编辑  收藏  举报