现在的位置: 首页 > 综合 > 正文

1051: [HAOI2006]受欢迎的牛

2018年01月13日 ⁄ 综合 ⁄ 共 1137字 ⁄ 字号 评论关闭
#include<iostream>
#include<cstdio>
#define N 10001
using namespace std;
struct edge{
    int to,next;
}e[50001],d[50001];
inline int read(){  
    int x=0,f=1;char ch=getchar();  
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}  
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}  
    return x*f;  
}  
int head[N],n,m,cnt,top,dfn[N],low[N],q[N],scc,h[N],belong[N],hav[N],ans;
bool vis[N],inq[N];
void dfs(int x){
    int now,i=head[x];
    vis[x]=inq[x]=1;
    low[x]=dfn[x]=++cnt;
    q[++top]=x;
    while(i){
        if(!vis[e[i].to]){
            dfs(e[i].to);
            low[x]=min(low[x],low[e[i].to]);
        }
        else if(inq[e[i].to])low[x]=min(low[x],dfn[e[i].to]);
        i=e[i].next;
    }
    if(low[x]==dfn[x]){
        scc++;
        while(now!=x){
            now=q[top--];
            inq[now]=0;
            belong[now]=scc;
            ++hav[scc];
        }
    }
}
void rebuild(){
    cnt=0;
    for(int i=1;i<=n;i++){
        int c=head[i];
        while(c){
            if(belong[i]!=belong[e[c].to]){
                d[++cnt].to=belong[e[c].to];
                d[cnt].next=h[belong[i]];
                h[belong[i]]=cnt;
            }
            c=e[c].next;
        }
    }
}
void tarjan(){
    for(int i=1;i<=n;i++)
        if(!vis[i])dfs(i);
    rebuild();
}
void work(){
    for(int i=1;i<=scc;i++)
        if(!h[i])
            if(ans){ans=0;return;}
                else ans=hav[i];
}
int main(){
    n=read();m=read();
    for(int i=1;i<=m;i++){
        int a=read(),b=read();
        e[i].to=b;e[i].next=head[a];head[a]=i;
    }
    tarjan();work();
    printf("%d",ans);
    return 0;
}

抱歉!评论已关闭.