Code:
#include <iostream> #include <cstdio> #include <cmath> #include <map> #include <queue># include<vector> #include <cstring> #include <algorithm> #define REP (i,a,b) for (int i= (a);i< (b); i+ +) #define REV (I,a,b) for (int i= (a); i>= (b); i--) #define CLR (a,x) memset (a,x,sizeof a) #define INF 0x3f3f3f3ftypedef Long long ll;using namespace std;const int Maxn=105;const int Maxm=maxn*maxn;int first[maxn],ecnt,v[maxm],nex[maxm];int Low[maxn],dfn[maxn],stck[maxn],belong[maxn];int index,top,scc;bool ins[maxn];int num[maxn];int IN[MAXN],OUT[MAXN]; int n,m;void Tarjan (int u) {low[u]=dfn[u]=++index; Stck[top++]=u; Ins[u]=1; for (int e=first[u];~e;e=nex[e]) {if (!dfn[v[e]]) {Tarjan (v[e]); Low[u]=min (Low[u],low[v[e]); } else if (Ins[v[e]]) low[u]=min (Low[u],dfn[v[e]]); } if (Low[u]==dfn[u]) {int V; scc++; do {v=stck[--top]; Ins[v]=false; BeLONG[V]=SCC; num[scc]++; }while (V!=u); }}void solve (int n) {clr (dfn,0); CLR (ins,0); CLR (num,0); Index=scc=top=0; for (int i=1;i<=n;i++) if (!dfn[i]) Tarjan (i);} void add_ (int a,int b) {v[ecnt]=b; Nex[ecnt]=first[a]; first[a]=ecnt++;} void Init () {ecnt=0; CLR (first,-1);} int main () {while (~SCANF ("%d", &n)) {init (); int ans1=0,ans2=0; for (int i=1;i<=n;i++) {while (~SCANF ("%d", &m) &&m) add_ (i,m); } solve (n); CLR (out,0); CLR (in,0); for (int i=1;i<=n;i++) for (int j=first[i];~j;j=nex[j]) if (Belong[i]!=belong[v[j]]) { out[belong[i]]++; in[belong[v[j]]]++; } for (int i=1;i<=scc;i++) {if (in[i]==0) ans1++; if (out[i]==0) ans2++; } if (scc==1) printf ("1\n0\n"); else printf ("%d\n%d\n", Ans1,max (ANS1,ANS2)); } return 0;}
POJ 1236 Network of schools (strongly connected component template problem)