5 2 4 3 0 4 5 0 0 0 1 0
1 2
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib> 10 #include <string> 11 #include <set> 12 #include <stack> 13 #define LL long long 14 #define pii pair<int,int> 15 #define INF 0x3f3f3f3f 16 using namespace std; 17 const int maxn = 110; 18 vector<int>g[maxn]; 19 stack<int>stk; 20 int dfn[maxn],low[maxn],belong[maxn],cnt,scc; 21 int n,in[maxn],out[maxn]; 22 bool instack[maxn]; 23 void tarjan(int u){ 24 dfn[u] = low[u] = ++cnt; 25 instack[u] = true; 26 stk.push(u); 27 for(int i = 0; i < g[u].size(); i++){ 28 if(!dfn[g[u][i]]){ 29 tarjan(g[u][i]); 30 low[u] = min(low[u],low[g[u][i]]); 31 }else if(dfn[g[u][i]] && instack[g[u][i]]) low[u] = min(low[u],dfn[g[u][i]]); 32 } 33 if(dfn[u] == low[u]){ 34 scc++; 35 int v; 36 do{ 37 v = stk.top(); 38 instack[v] = false; 39 stk.pop(); 40 belong[v] = scc; 41 }while(v != u); 42 } 43 } 44 int main(){ 45 int i,j,v; 46 while(~scanf("%d",&n)){ 47 for(i = 0; i <= n; i++){ 48 dfn[i] = low[i] = belong[i] = 0; 49 in[i] = out[i] = 0; 50 instack[i] = false; 51 g[i].clear(); 52 } 53 while(!stk.empty()) stk.pop(); 54 cnt = scc = 0; 55 for(i = 1; i <= n; i++) 56 while(scanf("%d",&v),v) g[i].push_back(v); 57 for(i = 1; i <= n; i++) if(!dfn[i]) tarjan(i); 58 for(i = 1; i <= n; i++){ 59 for(j = 0; j < g[i].size(); j++){ 60 if(belong[i] != belong[g[i][j]]){ 61 in[belong[g[i][j]]]++; 62 out[belong[i]]++; 63 } 64 } 65 } 66 int ans1 = 0,ans2 = 0; 67 for(i = 1; i <= scc; i++){ 68 if(!in[i]) ans1++; 69 if(!out[i]) ans2++; 70 } 71 printf("%d\n%d\n",ans1,scc == 1?0:max(ans1,ans2)); 72 } 73 return 0; 74 }