标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 13801 | Accepted: 5505 |
Description
Input
Output
Sample Input
5 2 4 3 0 4 5 0 0 0 1 0
Sample Output
1 2
题解:
代码:
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 #include<cmath> 6 #include<vector> 7 #include<stack> 8 #define mem(x,y) memset(x,y,sizeof(x)) 9 using namespace std; 10 const int INF=0x3f3f3f3f; 11 const int MAXN=110; 12 vector<int>vec[MAXN]; 13 stack<int>S; 14 int dfn[MAXN],low[MAXN],Instack[MAXN],in[MAXN],out[MAXN]; 15 int dfs_blocks,scc,sccon[MAXN]; 16 void targin(int u,int fa){ 17 S.push(u); 18 Instack[u]=1; 19 dfn[u]=low[u]=++dfs_blocks; 20 for(int i=0;i<vec[u].size();i++){ 21 int v=vec[u][i]; 22 if(!dfn[v]){ 23 targin(v,u); 24 low[u]=min(low[u],low[v]); 25 } 26 else if(Instack[v]){ 27 low[u]=min(low[u],dfn[v]); 28 } 29 } 30 if(low[u]==dfn[u]){ 31 scc++; 32 while(1){ 33 int v=S.top(); 34 S.pop(); 35 Instack[v]=0; 36 sccon[v]=scc; 37 if(u==v)break; 38 } 39 } 40 } 41 int main(){ 42 int N; 43 while(~scanf("%d",&N)){ 44 scc=0; 45 for(int i=0;i<MAXN;i++)vec[i].clear(); 46 while(!S.empty())S.pop(); 47 mem(in,0);mem(out,0);mem(Instack,0); 48 mem(dfn,0);mem(low,0);mem(sccon,0); 49 for(int i=1;i<=N;i++){ 50 int x; 51 while(scanf("%d",&x),x!=0){ 52 vec[i].push_back(x); 53 } 54 } 55 for(int i=1;i<=N;i++){ 56 if(!dfn[i]){ 57 targin(i,-1); 58 } 59 } 60 for(int i=1;i<=N;i++){ 61 for(int j=0;j<vec[i].size();j++){ 62 int v=vec[i][j]; 63 if(sccon[i]!=sccon[v])in[sccon[v]]++,out[sccon[i]]++; 64 } 65 } 66 // printf("%d\n",scc); 67 int numin=0,numout=0; 68 if(scc==1){ 69 puts("1\n0");continue; 70 } 71 for(int i=1;i<=scc;i++){ 72 if(in[i]==0)numin++; 73 if(out[i]==0)numout++; 74 } 75 printf("%d\n%d\n",numin,max(numin,numout)); 76 } 77 return 0; 78 }
Network of Schools(强连通分量+缩点) (问添加几个点最少点是所有点连接+添加最少边使图强连通)
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4905531.html