zoukankan      html  css  js  c++  java
  • poj1236 Network of Schools 强连通分量

    #include<cstdio>
    #include<algorithm>
    #include<vector>
    #include<cstring>
    #include<stack>
    using namespace std;
    
    const int maxn = 100 + 10;
    
    vector<int> G[maxn], G2[maxn];
    vector<int> S;
    int vis[maxn], sccno[maxn], scc_cnt;
    int in[maxn],out[maxn];
    
    int max(int a,int b)
    {
    	if(a>b) return a;
    	else return b;
    }
    void dfs1(int u) 
    {
        if(vis[u]) return;
        vis[u] = 1;
        for(int i = 0; i < G[u].size(); i++) dfs1(G[u][i]);
        S.push_back(u);
    }
    
    void dfs2(int u) 
    {
        if(sccno[u]) return;
        sccno[u] = scc_cnt;
        for(int i = 0; i < G2[u].size(); i++) dfs2(G2[u][i]);
    }
    
    void find_scc(int n) 
    {
    	int i;
        scc_cnt = 0;
        S.clear();
        memset(sccno, 0, sizeof(sccno));
        memset(vis, 0, sizeof(vis));
        for(i = 0; i < n; i++) dfs1(i);
        for(i = n-1; i >= 0; i--)
        if(!sccno[S[i]]) { scc_cnt++; dfs2(S[i]); }
    }
    int main()
    {
    	int n,i,j;
    	int u,v;
    	while(scanf("%d",&n)!=EOF)
    	{
    		for(i=0;i<n;i++)
    		{
    			G[i].clear();
    			G2[i].clear();
    		}
    		for(i=0;i<n;i++)
    		{
    			u=i;
    			while(scanf("%d",&v),v!=0)
    			{
    				v--;
    				G[u].push_back(v);
    				G2[v].push_back(u);
    			}
    		}
    		find_scc(n);
    		for(i=0;i<n;i++)
    		{
    			for(j=0;j<G[u].size();j++)
    			{
    				u=G[u][j];
    				if(sccno[i]!=sccno[u])
    				{
    					out[sccno[i]]++;
    					in[sccno[u]]++;
    				}
    			}
    		}
    		for(i = 1; i <= scc_cnt; i++) in[i]=out[i]=1;
    		for(u = 0; u < n; u++)
    			for(i = 0; i < G[u].size(); i++) 
    			{
    				v = G[u][i];
    				if(sccno[u] != sccno[v]) in[sccno[v]] = out[sccno[u]] = 0;
    			}
    		int a = 0, b = 0;
    		for(i = 1; i <= scc_cnt; i++) 
    		{
    			if(in[i]) a++;
    			if(out[i]) b++;
    		}
    		if(scc_cnt==1) printf("%d
    %d
    ",1,0);
    		else printf("%d
    %d
    ",a,max(a,b));
    	}
    	return 0;
    }
    
    
    


     

  • 相关阅读:
    UVA 254 Towers of Hanoi
    UVA 701 The Archeologists' Dilemma
    UVA 185 Roman Numerals
    UVA 10994 Simple Addition
    UVA 10570 Meeting with Aliens
    UVA 306 Cipher
    UVA 10160 Servicing Stations
    UVA 317 Hexagon
    UVA 10123 No Tipping
    UVA 696 How Many Knights
  • 原文地址:https://www.cnblogs.com/vermouth/p/3710167.html
Copyright © 2011-2022 走看看