Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 4373 | Accepted: 1710 |
Description
Input
Output
Sample Input
5
2 4 3 0
4 5 0
0
0
1 0
Sample Output
1
2
#include <iostream> #include <cstdio> #include <cstring> const int MAXN=101; bool con[MAXN][MAXN]; bool transpose[MAXN][MAXN]; int classify; int finish[MAXN]; bool visit[MAXN]; int sub; int distribute[MAXN]; int treenode[MAXN][MAXN]; int n; void dfs(int u) { int i; for(i=1;i<=n;i++) { if(con[u][i]==true&&visit[i]==false) { visit[i]=true; dfs(i); //sub++; //finish[sub]=i; } } sub++; finish[sub]=u; } void trandfs(int u) { int i; for(i=sub;i>=1;i--) { if(transpose[u][finish[i]]==1&&visit[finish[i]]==false) { distribute[finish[i]]=classify; visit[finish[i]]=true; trandfs(finish[i]); } } } int main() { int to; int i; int j; while(scanf("%d",&n)!=EOF) { memset(con,0,sizeof(con)); memset(transpose,0,sizeof(transpose)); for(i=1;i<=n;i++) { while(scanf("%d",&to),to) { con[i][to]=1; transpose[to][i]=1; } } memset(visit,0,sizeof(visit)); sub=0; for(i=1;i<=n;i++) { if(visit[i]==false) { visit[i]=true; dfs(i); // sub++; //finish[sub]=i; } }//DFS teh graph and compute finish time finish[u] for each vertex u memset(visit,0,sizeof(visit)); classify=0; for(i=sub;i>=1;i--) { if(visit[finish[i]]==false) { classify++; distribute[finish[i]]=classify; visit[finish[i]]=true; trandfs(finish[i]); } }//DFS the transpose graph follow the decrease finish time memset(treenode,0,sizeof(treenode)); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(con[i][j]==1) { if(distribute[i]!=distribute[j]) { treenode[distribute[i]][distribute[j]]=1; } } } }//construct the depth-first tree as the separate strongly connected componet int zeroindegree=0; for(i=1;i<=classify;i++) { zeroindegree++; for(j=1;j<=classify;j++) { if(treenode[j][i]==1) { zeroindegree--; break; } } }//compute the vertex which indegree is zero int zerooutdegree=0; for(i=1;i<=classify;i++) { zerooutdegree++; for(j=1;j<=classify;j++) { if(treenode[i][j]==1) { zerooutdegree--; break; } } }//compute the vertex which outdegree is zero printf("%d/n",zeroindegree); if(classify==1) { printf("0/n"); } else { if(zerooutdegree>zeroindegree) { printf("%d/n",zerooutdegree); } else { printf("%d/n",zeroindegree); } } } return 0; }