POJ 2186 Popular Cows / 强连通分量

强连通分量缩点 出度为0并且唯一一个强连通分量的大小是所求的答案 不唯一输出0

#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
const int maxn = 10010;

vector <int> G[maxn];
int pre[maxn];
int low[maxn];
int sccno[maxn];
int dfs_clock;
int scc_cnt;
stack <int> S;
int n, m;
int degree[maxn];
int cnt[maxn];
void dfs(int u)
{
	pre[u] = low[u] = ++dfs_clock;
	S.push(u);
	for(int i = 0; i < G[u].size(); i++)
	{
		int v = G[u][i];
		if(!pre[v])
		{
			dfs(v);
			low[u] = min(low[u], low[v]);
		}
		else if(!sccno[v])
			low[u] = min(low[u], pre[v]);
	}
	if(pre[u] == low[u])
	{
		scc_cnt++;
		while(1)
		{
			cnt[scc_cnt]++;
			int x = S.top();
			S.pop();
			sccno[x] = scc_cnt;
			if(x == u)
				break;
		}
	}
}
void find_scc()
{
	dfs_clock = scc_cnt = 0;
	memset(sccno, 0, sizeof(sccno));
	memset(pre, 0, sizeof(pre));
	memset(cnt, 0, sizeof(cnt));
	for(int i = 1; i <= n; i++)
		if(!pre[i])
			dfs(i);
}

int main()
{
	while(scanf("%d %d", &n, &m) != EOF)
	{
		for(int i = 1; i <= n; i++)
			G[i].clear();
		while(m--)
		{
			int u, v;
			scanf("%d %d", &u, &v);
			G[u].push_back(v);
		}
		find_scc();
		memset(degree, 0, sizeof(degree));
		for(int i = 1; i <= n; i++)
		{
			for(int j = 0; j < G[i].size(); j++)
			{
				int v = G[i][j];
				if(sccno[i] != sccno[v])
				{
					degree[sccno[i]]++;
				}
			}
		}
		int flag = 0;
		int p = 1;
		for(int i = 1; i <= scc_cnt; i++)
		{
			if(degree[i] == 0)
			{
				flag++;
				p = i;
			}
		}
		if(flag > 1)
			printf("0\n");
		else
			printf("%d\n", cnt[p]);
	}
	return 0;
}


 

你可能感兴趣的:(POJ 2186 Popular Cows / 强连通分量)