Popular Cows

来源:互联网 发布:php网站模板下载不了 编辑:程序博客网 时间:2024/05/16 18:07

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 33977 Accepted: 13845
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
做法:
先跑一遍taijian算法。那么出度为0的强连通分量代表的就是受其他奶牛欢迎的,但是如果出度为0的强连通分量的个数大于1.那么则无解。因为将至少有两个分量里的奶牛互相不喜欢。所以我们的算法就是如果出度为0的强连通分量的个数是1.那么我们算出这里面点的个数就是最后的答案。
代码如下:

#include <iostream>#include <cstdio>using namespace std;struct  arr{    int x,y,n;};arr f[60000];int be[60000],dfn[60000],low[60000],s[60000],cd[60000],ls[60000],bcnt=0,tot=0,n,m,d=0,s1=0;bool ins[60000];void tarjan(int i){    int t=0,j=0;    d++;    dfn[i]=d;    low[i]=d;    tot++;    ins[i]=1;    s[tot]=i;    t=ls[i];    while (t!=0)    {        j=f[t].y;        if (dfn[j]==0)        {            tarjan(j);            if (low[i]>low[j])  low[i]=low[j];        }        else if (ins[j]&&dfn[j]<low[i]) low[i]=dfn[j];        t=f[t].n;    }    if (dfn[i]==low[i])    {        bcnt++;        do        {            j=s[tot];            tot--;            ins[j]=0;            be[j]=bcnt;        }        while (i!=j);    }}int main(){    cin>>n>>m;    d=0;tot=0;    for (int i=1;i<=m;i++)    {        cin>>f[i].x>>f[i].y;        f[i].n=ls[f[i].x];        ls[f[i].x]=i;    }    int j=0;    for (int i=1;i<=n;i++)        if (dfn[i]==0)  tarjan(i);    for (int i=1;i<=m;i++)        if (be[f[i].x]!=be[f[i].y]) cd[be[f[i].x]]++;    for (int i=1;i<=bcnt;i++)        if (cd[i]==0)   {s1++;  j=i;}    int ans=0;    for (int i=1;i<=n;i++)        if (be[i]==j)   ans++;    if (s1!=1)  ans=0;    cout<<ans<<endl;}
原创粉丝点击