水题,直接贴代码。
//poj 3180 //sep9 #include <iostream> #include <stack> using namespace std; const int maxN=10024; const int maxM=50048; int sum[maxN]; int head[maxN],dfn[maxN],low[maxN],ins[maxN],belong[maxN]; stack<int> s; struct Edge{ int v,next; }edge[maxM]; int n,m,e,t,cnt; void tarjan(int u){ dfn[u]=low[u]=++t; s.push(u); ins[u]=1; for(int i=head[u];i!=-1;i=edge[i].next){ int v=edge[i].v; if(dfn[v]==0){ tarjan(v); low[u]=min(low[u],low[v]); }else if(ins[v]==1) low[u]=min(low[u],dfn[v]); } int k; if(low[u]==dfn[u]){ ++cnt; do{ k=s.top(); s.pop(); ins[k]=0; belong[k]=cnt; }while(low[k]!=dfn[k]); } return ; } int main() { int n,m; scanf("%d%d",&n,&m); e=0; memset(head,-1,sizeof(head)); memset(dfn,0,sizeof(dfn)); memset(ins,0,sizeof(ins)); while(m--){ int a,b; scanf("%d%d",&a,&b); edge[e].v=b;edge[e].next=head[a];head[a]=e++; } t=cnt=0; for(int i=0;i<n;++i) if(!dfn[i]) tarjan(i); memset(sum,0,sizeof(sum)); for(int i=0;i<n;++i) ++sum[belong[i]]; int ans=0; for(int i=1;i<=cnt;++i) if(sum[i]>1) ++ans; printf("%d",ans); return 0; }
时间: 2024-10-12 06:57:14