poj 2186(强连通分量)

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 14393 Accepted: 5718

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. 

Source

分析:这题首先想到的就是求强连通缩点,然后计算出度为0的点的个数,如果为1,即答案所求,否则无解,输出0;
代码:
#include<cstdio>
#define min(a,b) a<b?a:b
using namespace std;
const int mm=50005;
const int mn=10001;
int s[mm],t[mm],p[mm];
int h[mn],id[mn],q[mn],dfn[mn],low[mn],num[mn];
int i,j,k,n,m,tsp,qe,cnt;
void dfs(int u)
{
    int i,v;
    dfn[u]=low[q[qe++]=u]=++tsp;
    for(i=h[u];i>=0;i=p[i])
        if(!dfn[v=t[i]])
            dfs(v),low[u]=min(low[u],low[v]);
        else if(id[v]<0)low[u]=min(low[u],dfn[v]);
    if(low[u]==dfn[u])
    {
        num[id[u]=++cnt]=1;
        while((v=q[--qe])!=u)++num[id[v]=cnt];
    }
}
void tarjan()
{
    int i;
    for(tsp=qe=cnt=i=0;i<=n;++i)id[i]=-1,dfn[i]=0;
    for(i=1;i<=n;++i)
        if(!dfn[i])dfs(i);
}
int main()
{
    while(scanf("%d%d",&n,&m)!=-1)
    {
        for(i=0;i<=n;++i)h[i]=-1;
        for(k=0;k<m;++k)
        {
            scanf("%d%d",&i,&j);
            s[k]=i,t[k]=j,p[k]=h[i],h[i]=k;
        }
        tarjan();
        for(i=0;i<=cnt;++i)q[i]=0;
        for(i=0;i<m;++i)
            if((j=id[s[i]])!=id[t[i]])++q[j];
        for(tsp=0,i=1;i<=cnt;++i)
            if(!q[i])++tsp,j=i;
        if(tsp>1)printf("0\n");
        else printf("%d\n",num[j]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值