您的位置:首页 > 运维架构

POJ 2186 Popular Cows

2017-04-02 23:30 302 查看

Popular Cows

Time Limit: 2000MS


Memory Limit: 65536K

Total Submissions: 32921


Accepted: 13413

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.

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;
#define mst(a,b) memset(a,(b),sizeof(a))
#define f(i,a,b) for(int i=a;i<b;i++)
#define maxn 10005
int low[maxn],dfn[maxn],vis[maxn];
int instack[maxn],color[maxn],in[maxn];
int n,m,tot,num;
int x[50005],y[50005];
vector<int>G[maxn];
stack<int>S;
void init()
{
tot=num=0;
f(i,0,n+1)
{
G[i].clear();
low[i]=dfn[i]=vis[i]=0;
instack[i]=color[i]=in[i]=0;
}
while(!S.empty())
{
S.pop();
}
}
void tarjan(int x)
{
low[x]=dfn[x]=tot++;
vis[x]=instack[x]=1;
S.push(x);
f(i,0,G[x].size())
{
int v=G[x][i];
if(!vis[v])
{
tarjan(v);
low[x]=min(low[x],low[v]);
}
else if(instack[v])
{
low[x]=min(low[x],dfn[v]);
}
}
if(low[x]==dfn[x])
{
while(1)
{
int v=S.top();
S.pop();
instack[v]=0;
color[v]=num;
if(v==x)
break;
}
num++;
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
init();
f(i,0,m)
{
scanf("%d%d",&x[i],&y[i]);
G[y[i]].push_back(x[i]);
}
f(i,1,n+1)
{
if(!vis[i])
tarjan(i);
}
f(i,0,m)
{
if(color[x[i]]!=color[y[i]])
in[color[x[i]]]++;
}
int ans=0;
f(i,0,num)
{
if(in[i]==0)
ans++;
}
if(ans>1)
printf("0\n");
else
{
ans=0;
f(i,1,n+1)
{
if(in[color[i]]==0)
ans++;
}
printf("%d\n",ans);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: