滴,集训第二十七天打卡。
近日居然没有新的题目训练了呢...
有点无趣,只能翻之前的题目补补了..
POJ 2186 Popular Cows
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.
题目大意:有N头牛,有M种关系,1崇拜2,2崇拜1,2崇拜3,崇拜可以传递,问存在几头牛被所有牛都崇拜。
思路:给出的图会有不连通的可能,则输出零,如果缩点后有多个出度为零的点,也输出零。求树上的节点有多少个出度为零,如果有一个就输出那个点里包含的所有点。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <stack>
using namespace std;
struct Edge
{
int v,next;
}eg[50050];
int head[10010],vis[10010];
int dfn[10010],low[10010],pre[10010],in[10010];
bool can[10010];
int n,tp,tmm;
stack <int> s;
void tarjan(int u)
{
int v,i,x;
s.push(u);
vis[u]=1;
low[u]=dfn[u]=tmm++;
for(i=head[u];i!=-1;i=eg[i].next)
{
v=eg[i].v;
if(vis[v]==0)
{
tarjan(v);
vis[v]=1;
low[u]=min(low[u],low[v]);
}
else if(vis[v]==1)
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
x=s.top();
while(x!=u)
{
pre[x]=u;
s.pop();
x = s.top();
}
pre[x]=u;
s.pop();
}
}
int main()
{
int u,v,i,j,f;
while(~scanf("%d%d",&n,&tp))
{
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
memset(in,0,sizeof(in));
memset(can,0,sizeof(can));;
for(i=0;i<tp;i++)
{
scanf("%d%d",&u,&v);
eg[i].v=v;
eg[i].next=head[u];
head[u]=i;
}
for(i=1;i<=n;i++)
{
if(vis[i]) continue;
tmm=0;
tarjan(i);
}
f=0;
for(i=1;i<=n;i++)
{
for(j=head[i];j!=-1;j=eg[j].next)
{
v=eg[j].v;
if(pre[v]!= pre[i])
in[i]++;
}
if(in[i])
can[pre[i]]=1;
}
int cnt=0;
for(i=1;i<=n;i++)
{
if(pre[i]==i&&!can[i])
{
f=i;
cnt++;
}
if(cnt>1) break;
}
if(cnt!=1)
printf("0\n");
else
{
cnt = 0;
for(i=1;i<=n;i++)
{
if(pre[i]==f)
cnt++;
}
printf("%d\n",cnt);
}
}
return 0;
}