Test instructions: There are n cows, and some like relationships, cow A likes cow B, this relationship can be passed, asking how many cows are on the ranch all cows like.
First strong connectivity, because in the same strong connected component of the cow is equivalent, and then for a direction-free graph to see if there is only one strong connectivity component out of 0, if so, then the strong connected component of the point is the answer, otherwise 0.
1#include <stdio.h>2#include <string.h>3#include <stack>4#include <queue>5 using namespacestd;6 7 Const intmaxn=10005;8 Const intmaxm=50005;9 Ten inthead[maxn],point[maxm],nxt[maxm],size; One intn,t,scccnt; A intSTX[MAXN],LOW[MAXN],SCC[MAXN],OD[MAXN]; -stack<int>S; - the voidinit () { -memset (head,-1,sizeof(head)); -Size=0; -memset (OD,0,sizeof(OD)); + } - + voidAddintAintb) { Apoint[size]=b; atnxt[size]=Head[a]; -head[a]=size++; - } - - voidDfsints) { -stx[s]=low[s]=++T; in S.push (S); - for(intI=head[s];~i;i=Nxt[i]) { to intj=Point[i]; + if(!Stx[j]) { - Dfs (j); thelow[s]=min (low[s],low[j]); * } $ Else if(!Scc[j]) {Panax Notoginsenglow[s]=min (low[s],stx[j]); - } the } + if(low[s]==Stx[s]) { Ascccnt++; the while(1){ + intu=S.top (); S.pop (); -scc[u]=scccnt; $ if(S==u) Break; $ } - } - } the - voidSETSCC () {Wuyimemset (STX,0,sizeof(STX)); thememset (SCC,0,sizeof(SCC)); -T=scccnt=0; Wu for(intI=1; i<=n;++i)if(!Stx[i]) DFS (i); - for(intI=1; i<=n;++i) { About for(intj=head[i];~j;j=Nxt[j]) { $ intk=Point[j]; - if(scc[i]!=Scc[k]) { -od[scc[i]]++; - } A } + } the } - $ intMain () { the intm; the while(SCANF ("%d%d", &n,&m)! =EOF) { the init (); the while(m--){ - intb; inscanf"%d%d",&a,&b); the Add (A, b); the } About SETSCC (); the intans=0; the if(scccnt==1) printf ("%d\n", n); the Else{ + for(intI=1; i<=scccnt;++i)if(!od[i]) ans++; - if(ans!=1){ theprintf"0\n");Bayi } the Else{ theans=0; - for(intI=1; i<=n;++i) { - if(!od[scc[i]]) ans++; the } theprintf"%d\n", ans); the } the } - } the return 0; the}
View Code
poj2186 Strong Connectivity