7GOJ 学院 [连通性][并查集/DFS]

题意:询问一个图中有多少个环与链。
其实跑一遍DFS+vis标记就行了,随手打上并查集。。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=200010;
const int mod=1000000007;
long long tot,ans=1;
int fa[N],sz[N],sum[N],n,m;
bool vis[N];
inline int find(int x){
    return fa[x]==x?x:fa[x]=find(fa[x]);
}
inline void unionn(int x,int y){
    register int fx=find(x),fy=find(y);
    if(fx!=fy)fa[fx]=fy,sz[fy]+=sz[fx],sum[fy]+=sum[fx];
    else ++sum[fx];
}
inline void read(int &res){
    static char ch;int flag=1;
    while((ch=getchar())<'0'||ch>'9')if(ch=='-')flag=-1;res=ch-48;
    while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-48;res*=flag;
}
int main(){
    freopen("school.in","r",stdin);
    freopen("school.out","w",stdout);
    read(n),read(m);
    for(register int i=1;i<=n;i++)fa[i]=i,sz[i]=1;
    for(register int x,y,i=1;i<=m;i++)
        read(x),read(y),unionn(x,y);
    for(register int i=1;i<=n;i++){
        int fx=find(i);
        if(!vis[fx]){
            vis[fx]=1;
            if(sum[fx]==0)ans=(ans*sz[fx])%mod;//Á´ 
            else if(sum[fx]==1)ans=(ans*2)%mod;//×Գɻ· 
            else ans=0;//Êý¾ÝÕæµÄºÏ·¨£¿ 
        }
    }
    cout<<ans<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值