Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 37486 | Accepted: 15293 |
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.
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.
* 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.
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
struct node {
int v,next;
}edge[1001];
int DFN[1001],LOW[1001];
int stack[1001],heads[1001],visit[1001],cnt,tot,index;
vector<int>v[10005],v1[10005];
int p=0,num[10005],d[10005];
void add(int x,int y)
{
edge[++cnt].next=heads[x];
edge[cnt].v = y;
heads[x]=cnt;
return ;
}
void tarjan(int x)//代表第几个点在处理。递归的是点。
{
DFN[x]=LOW[x]=++tot;// 新进点的初始化。
stack[++index]=x;//进站
visit[x]=1;//表示在栈里
for(int i=heads[x];i!=-1;i=edge[i].next)
{
if(!DFN[edge[i].v]) {//如果没访问过
tarjan(edge[i].v);//往下进行延伸,开始递归
LOW[x]=min(LOW[x],LOW[edge[i].v]);//递归出来,比较谁是谁的儿子/父亲,就是树的对应关系,涉及到强连通分量子树最小根的事情。
}
else if(visit[edge[i].v ]){ //如果访问过,并且还在栈里。
LOW[x]=min(LOW[x],DFN[edge[i].v]);//比较谁是谁的儿子/父亲。就是链接对应关系
}
}
if(LOW[x]==DFN[x]) //发现是整个强连通分量子树里的最小根。
{
do{
//printf("%d ",stack[index]);
v[p].push_back(stack[index]);//存每个强连通分量
visit[stack[index]]=0;
index--;
num[stack[index]]=p;
}while(x!=stack[index+1]);//出栈,并且输出。
// printf("\n");
p++;
}
return ;
}
int main()
{
memset(heads,-1,sizeof(heads));
int n,m,i,j;
scanf("%d%d",&n,&m);
int x,y;
for( i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
v1[x].push_back(y);
}
for(int i=1;i<=n;i++)
if(!DFN[i]) tarjan(i);//当这个点没有访问过,就从此点开始。防止图没走完
/*for(i=0;i<p;i++)
//{
/*for(j=0;j<v[i].size();j++)
{
printf("%d ",v[i][j]);
}
printf("\n");//输出强连通分量
} */
memset(d,sizeof(d),0);
for(i=0;i<p;i++)
{
for(j=0;j<v1[i].size();j++)
{
if(num[i]!=num[v1[i][j]])//看是否属于一个强连通分量
{
d[num[i]]++;//缩点
}
}
}
int res=0,loc;
for(i=0;i<p;i++)
{
if(d[i]==0)//出度为0
{
res++;
loc=i;
}
}
if(res>1)
printf("0");
else
printf("%d",v[loc].size());
return 0;
}