POJ 2186 Popular Cows (强连通分量)

题意:—给定一个有向图,求有多少个顶点是由任何顶点出发都可达的。
题解:1. 求出所有强连通分量  2. 每个强连通分量缩成一点,则形成一个有向无环图DAG。—3. DAG上面如果有唯一的出度为0的点,则该点能被所有的点可达。那么该点所代表的连通分量上的所有的原图中的点,都能被原图中的所有点可达,则该连通分量的点数,就是答案。—4. DAG上面如果有不止一个出度为0的点,则这些点互相不可达,原问题无解,答案为0

PS:有向无环图中唯一出度为0的点,一定可以由任何点出发均可达(由于无环,所以从任何点出发往前走,必然终止于一个出度为0的点)

#include <iostream>
using namespace std;

#define N 10009
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)

int n, m;
int size, cnt, top, id;
int instack[N], stack[N];
int head[N], low[N], dfn[N];
int out[N], block[N], num[N];
struct Edge { int v, next; } edge[N*5];

void Tarjan ( int u )
{  
	int v;
	instack[u] = 1;  
	stack[++top] = u;  
	dfn[u] = low[u] = ++id;  
	
	for ( int i = head[u]; i; i = edge[i].next )
	{  
		v = edge[i].v;
		if ( ! dfn[v] )
		{  
			Tarjan(v);  
			low[u] = min ( low[u], low[v] );  
		}  
		else if ( instack[v] ) //instack保证不是横叉边
			low[u] = min ( low[u], dfn[v] ); //注意不是 min(low[u],low[v])!
	}  
	
	if ( low[u] == dfn[u] )
	{  
		cnt++;  
		do {
		    v = stack[top--];  
			instack[v] = 0;  
			block[v] = cnt; 
			num[cnt]++;
        } while ( u != v );  
	}  
}  

int shrink ()
{
	int u, v, i, ans, flag = 0;
	for ( u = 1; u <= n; u++ )
	{
		for ( i = head[u]; i; i = edge[i].next )
		{
			v = edge[i].v;
			if ( block[u] != block[v] )
				out[block[u]]++;
		}
	}

	for ( i = 1; i <= cnt; i++ )
	{
		if ( out[i] == 0 )
		{ 
			ans = num[i];
			flag++;
		}
		if ( flag > 1 )
		{
			ans = 0; break;
		}
	}
	return ans;
}

void Initial()
{
	size = cnt = id = top = 0;
	for ( int i = 1; i <= n; i++ )
	{
		out[i] = block[i] = num[i] = 0;
		head[i] = instack[i] = dfn[i] = 0;
	}
}

void add ( int u, int v )
{
	size++;
	edge[size].v = v;
	edge[size].next = head[u];
	head[u] = size;
}

int main()
{
	int u, v;
	Initial();
	scanf("%d%d",&n,&m);
	while ( m-- )
	{
		scanf("%d%d",&u,&v);
		add(u,v);
	}
	for ( v = 1; v <= n; v++ )
	    if ( ! dfn[v] ) Tarjan ( v ); 
	printf("%d\n", shrink() );
	return 0;
}



你可能感兴趣的:(struct)