POJ 1286:Popular Cows【强连通】

Popular Cows

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 13   Accepted Submission(s) : 2
Problem 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
  AC—code:
#include<cstdio>
#include<cstring>
#include<vector>
#include<stack>
#define min(a,b) a>b?b:a
#define MAXN 10005
#define MAXM 50005
using namespace std;
int head[MAXM],low[MAXN],dfn[MAXN],sccno[MAXN],instack[MAXN];
stack<int>s;
vector<int>scc[MAXN];
vector<int>G[MAXN];
int num,scc_cnt,dfs_clock;
struct Eage
{
	int from,to,next;
}eage[MAXM];
void add(int a,int b)
{
	eage[num].from=a;
	eage[num].to=b;
	eage[num].next=head[a];
	head[a]=num++;
}

void tarjan(int u)
{
	int v;
	low[u]=dfn[u]=++dfs_clock;
	s.push(u);
	instack[u]=1;
	for(int i=head[u];i!=-1;i=eage[i].next)
	{
		v=eage[i].to;
		if(!dfn[v])
		{
			tarjan(v);
			low[u]=min(low[u],low[v]);
		}
		else if(instack[v])
			low[u]=min(dfn[v],low[u]);
	}
		if(dfn[u]==low[u])
		{
			scc_cnt++;
			scc[scc_cnt].clear();
			do
			{
				v=s.top();
				s.pop();
				instack[v]=0;
				sccno[v]=scc_cnt;
				scc[scc_cnt].push_back(v);
			}while(u!=v);
		}
}
int in[MAXN];
int main()
{
	int n,m,i,j,a,b;
	scanf("%d%d",&n,&m);
	memset(head,-1,sizeof(head));
	num=0;
	for(i=0;i<m;i++)
	{
		scanf("%d%d",&a,&b);
		add(a,b);
	}
	memset(dfn,0,sizeof(dfn));
	memset(low,0,sizeof(low));
	memset(sccno,0,sizeof(sccno));
	memset(instack,0,sizeof(instack));
	dfs_clock=scc_cnt=0;
	for(i=1;i<=n;i++)
		if(!dfn[i])
			tarjan(i);
	int x,sum=0;
	memset(in,0,sizeof(in));
	for(i=1;i<=n;i++)
		for(j=head[i];j!=-1;j=eage[j].next)
			if(sccno[i]!=sccno[eage[j].to])
			{
				in[sccno[i]]=1;
				break;
			}
	for(i=1;i<=scc_cnt;i++)
		if(!in[i])
		{
			sum++;
			x=i;
		}
	if(sum==1)
	{
		sum=0;
		for(i=1;i<=n;i++)
		{
			if(sccno[i]==x)
				sum++;
		}
		printf("%d\n",sum);
	}
	else
		printf("0\n");
	return 0;
}

你可能感兴趣的:(动态规划,poj,强连通)