POJ2186——Popular Cows

Description

Every cow's dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.

Input

* Line 1: Two space-separated integers, N and M

* Lines 2..1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.

Output

* Line 1: A single integer that is the number of cows who are considered popular by every other cow.

Sample Input

3 3
1 2
2 1
2 3

Sample Output

1

Hint

Cow 3 is the only cow of high popularity.

Source

USACO 2003 Fall


看完这题,我的想法就是tarjan然后缩点,但是最后一个地方想错了,导致了WA,只能说自己想的不够仔细

我的想法是,缩点以后,找出入度为强连通分量数-1的点,然后加起来,其实这是错误的

比如:1->2 ,3->2,2->4,这样4是符合的,但是4的入度并不是3

正解是寻找出度为0的点,因为这个点既然有边指向它,那么它一定没有边指出去,否则就与其他点连通了,当然如果这样的点超过1个,那么是无解的,因为他们自身不能指向对方。

#include<cstdio>
#include<string>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn=10006;
int DFN[maxn];
int low[maxn];
int sccnum[maxn];
int in[maxn];
int out[maxn];
int num[maxn];
int stack[maxn];
bool instack[maxn];
struct node
{
	int next;
	int to;
}edge[maxn*5];
int head[maxn];
int tot,top,index,sccNum,n;

void addedge(int from,int to)
{
	edge[tot].to=to;
	edge[tot].next=head[from];
	head[from]=tot++;
}

void tarjan(int u)
{
	DFN[u]=low[u]=++index;
	stack[top++]=u;
	instack[u]=1;
	for(int i=head[u];i!=-1;i=edge[i].next)
	{
		int v=edge[i].to;
		if(DFN[v]==0)
		{
			tarjan(v);
			if(low[u]>low[v])
			   low[u]=low[v];
		}
		else if(instack[v])
		    if(low[u]>DFN[v])
		       low[u]=DFN[v];
	}
	if(DFN[u]==low[u])
	{
		sccNum++;
		do
		{
			top--;
			sccnum[stack[top]]=sccNum;
			num[sccNum]++;
			instack[stack[top]]=0;
		}while(stack[top]!=u);
	}
}

void solve()
{
	memset(instack,0,sizeof(instack));
	memset(num,0,sizeof(num));
	memset(DFN,0,sizeof(DFN));
	memset(in,0,sizeof(in));
	memset(out,0,sizeof(out));
	index=0;
	top=0;
	sccNum=0;
	for(int i=1;i<=n;i++)
	  if(DFN[i]==0)
	     tarjan(i);
}

int main()
{
	int m;
	while(~scanf("%d%d",&n,&m))
	{
		int x,y;
		tot=0;
		memset(head,-1,sizeof(head));
		for(int i=0;i<m;i++)
		{
			scanf("%d%d",&x,&y);
			addedge(x,y);
		}
		solve();
		for(int i=1;i<=n;i++)
		{
			for(int j=head[i];j!=-1;j=edge[j].next)
			{
				if(sccnum[i]!=sccnum[edge[j].to])
				{
					out[sccnum[i]]++;
					in[sccnum[edge[j].to]]++;
				}
			}
		}
		int ans=0,j,i,cnt=0;
		for(i=1;i<=sccNum;i++)
		{
			if(out[i]==0)
   			{
   				cnt++;
   			}
		}
		if(cnt>1 || cnt==0)
			printf("0\n");
		else
		    printf("%d\n",num[cnt]);
	}
	return 0;
}


你可能感兴趣的:(图的连通性)