传送门:http://poj.org/problem?id=3180
解题思路:
#include <cstdio> #include <algorithm> #include <cstring> #include <map> #include <iostream> using namespace std; const int MAXN=10010; const int MAXM=50010; struct Edge{ int to; int next; }edge[MAXM]; int head[MAXN]; int tot; void addEdge(int u,int v){ edge[tot].to=v; edge[tot].next=head[u]; head[u]=tot++; } void init(){ memset(head,-1,sizeof(head)); tot=0; } int LOW[MAXN],DFS[MAXN],Stack[MAXN],Num[MAXN],Belong[MAXN]; bool Instack[MAXN]; int Index; int scc; int top; void Targan(int u){ LOW[u]=DFS[u]=++Index; Stack[top++]=u; Instack[u]=true; int v; for(int i=head[u];i!=-1;i=edge[i].next){ v=edge[i].to; if(!DFS[v]){ Targan(v); if(LOW[u]>LOW[v]) LOW[u]=LOW[v]; }else if(Instack[v]&&LOW[u]>DFS[v]){ LOW[u]=DFS[v]; } } if(LOW[u]==DFS[u]){ scc++; do{ v=Stack[--top]; Instack[v]=false; Belong[v]=scc; Num[scc]++; }while(v!=u); } } void Solve(int n){ memset(Instack,false,sizeof(Instack)); memset(DFS,0,sizeof(DFS)); memset(Num,0,sizeof(Num)); Index=scc=top=0; for(int i=1;i<=n;i++) if(!DFS[i]) Targan(i); } int main(){ int n,m; scanf("%d%d",&n,&m); init(); for(int i=0;i<m;i++){ int u,v; scanf("%d%d",&u,&v); addEdge(u,v); } Solve(n); int ans=0; for(int i=1;i<=scc;i++) if(Num[i]>=2) ans++; cout<<ans<<endl; }
时间: 2024-10-20 13:48:08