POJ 2186 Popular Cows(缩点+出度判断)

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions:36908 Accepted: 15026

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

题解:
强连通分量缩点。成为一个有向无环图。若有两个以上的点
出度为0,则这两个点一定不会产生关系,若有一个点出度
为0,则这个点所包含的连通分量的个数便是答案的解。

代码:

#include<cstdio>
#include<string.h>
#include<stack>
using namespace std;
const int maxn=10007;
int head[maxn],dfn[maxn],low[maxn],tol;
int from[maxn*5],to[maxn*5],vis[maxn];
int out[maxn],par[maxn],num,sum[maxn];
stack<int>P;
struct node
{
    int to,next;
}rode[maxn*5];
void add(int a,int b)
{
    rode[tol].to=b;
    rode[tol].next=head[a];
    head[a]=tol++;
}
void tarjan(int x)
{
    P.push(x);
    vis[x]=1;
    dfn[x]=low[x]=++tol;
    for(int i=head[x];i!=-1;i=rode[i].next)
    {
        node e=rode[i];
        if(!vis[e.to])tarjan(e.to);
        if(vis[e.to])low[x]=min(low[x],low[e.to]);
    }
    if(dfn[x]==low[x])
    {
        num++;int v;
        sum[num]=0;
        do
        {
            v=P.top();P.pop();
            sum[num]++;
            par[v]=num;
        }while(v!=x);
    }
}
int main()
{
    int n,m,i,j;tol=0;
    scanf("%d%d",&n,&m);
    memset(head,-1,sizeof(head));
    memset(vis,0,sizeof(vis));
    memset(out,0,sizeof(out));
    memset(in,0,sizeof(in));
    for(i=1;i<=m;i++)
    {
        scanf("%d%d",&from[i],&to[i]);
        add(from[i],to[i]);
    }
    tol=num=0;
    for(i=1;i<=n;i++)
        if(!vis[i])tarjan(i);
    for(i=1;i<=m;i++)
    {
        int x=from[i],y=to[i];
        x=par[x];y=par[y];
        if(x!=y)
        {
            out[x]++;
        }
    }
    int ans=0,cnt=0;
    for(i=1;i<=num;i++)
    {
        if(out[i]==0)cnt++,ans=sum[i];
    }
    if(cnt>1)ans=0;
    printf("%d\n",ans);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值