poj2186 Popular Cows(tarjan缩点)

Topic Link

Meaning of the questions : There are n cattle, m kinds of worship relations. Such a cult bovine cattle b, bovine cattle worship B c, then a cow to cow worship c. I asked how many cows are worshiped all cattle.

 

Interpretations : Relationship worship certainly there is formed a directed acyclic graph, all cows in a strong Unicom component is reduced in a point to point. Then on the simple, all remaining points were not strong Unicom, into a directed acyclic graph. As long as we find out the degree of zero point, be able to find all cow worship cattle. If you do not find the answer is 0; if one is found, because this point may be a point strongly connected component shrunk to the super, so the output of all connected components contained in this cow. If more than 2, then the two are not mutually cow worship, all the answers is also 0;

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1e4+100;
struct edge{
	int next,v;
}e[maxn*5];
int head[maxn],vis[maxn],dfn[maxn],low[maxn],col[maxn],du[maxn],sum[maxn],stack[maxn];
int tot,cnt,index,colnum;
void insert(int u,int v){
	e[++tot].v=v;e[tot].next=head[u];head[u]=tot;
}
void tarjan(int u){
	dfn[u]=low[u]=++cnt;
	stack[++index]=u;
	vis[u]=1;
	for(int i=head[u];i;i=e[i].next){
		int v = e[i].v;
		if(!dfn[v]){
			tarjan(v);
			low[u]=min(low[u],low[v]);
		}
		else if(vis[u]) low[u]=min(low[u],dfn[v]);
	}
	if(low[u]==dfn[u]){
		colnum++;
		do{
			col[stack[index]]=colnum;//进行缩点 
			sum[colnum]++;//每个连通分量牛的个数 
			vis[stack[index--]]=0;
		}while(u!=stack[index+1]);
	}
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++){
		int u,v;
		scanf("%d%d",&u,&v);
		insert(u,v);
	}
	for(int i=1;i<=n;i++)
	if(!dfn[i]) tarjan(i);
	
	for(int i=1;i<=n;i++){
		for(int j=head[i];j;j=e[j].next){
			int v = e[j].v; 
			if(col[i]!=col[v]){
				du[col[i]]++;//出度加1 
			}
		}
	}
	
	int temp=0,ans=0;
	for(int i=1;i<=colnum;i++){
		if(du[i]==0){
			temp++;
			ans=sum[i];
		}
	}
	if(temp==0) puts("0");
	else {
		if(temp>1) puts("0");
		else {
			printf("%d\n",ans);
		}
	}
 } 

 

Guess you like

Origin blog.csdn.net/qq_42129242/article/details/90905549