poj 1236 Network of Schools
#include <cstdio> #include <cstring> #include <algorithm> #include <stack> #include <vector> using namespace std; int n,dfn[110],low[110],scc[110],scc_cnt,dfs_clock,inx[110],outx[110],a,b; stack<int> s; vector<int> G[110]; void dfs(int u){ dfn[u]=low[u]=++dfs_clock; s.push(u); for(int i=0;i<G[u].size();i++){ int v=G[u][i]; if(!dfn[v]){ dfs(v); low[u]=min(low[u],low[v]); } else if(!scc[v])low[u]=min(low[u],dfn[v]); } if(dfn[u]==low[u]){ scc_cnt++; for(;;){ int x=s.top(); s.pop(); scc[x]=scc_cnt; if(x==u)break; } } } int main(){ while(scanf("%d",&n)!=EOF){ dfs_clock=scc_cnt=a=b=0; for(int i=1;i<=n;i++)G[i].clear(); memset(dfn,0,sizeof(dfn)); memset(scc,0,sizeof(scc)); memset(inx,0,sizeof(inx)); memset(outx,0,sizeof(outx)); for(int u=1;u<=n;u++){ int v; while(scanf("%d",&v) && v!=0){ G[u].push_back(v); } } for(int i=1;i<=n;i++)if(!scc[i])dfs(i); for(int u=1;u<=n;u++) for(int i=0;i<G[u].size();i++){ int v=G[u][i]; if(scc[u]!=scc[v]){inx[scc[v]]++; outx[scc[u]]++;} } for(int u=1;u<=scc_cnt;u++){ if(!inx[u])a++; if(!outx[u])b++; } printf("%d\n",a); if(scc_cnt==1)puts("0"); else printf("%d\n",max(a,b)); } return 0; }