POJ 2186 Popular Cows


Popular Cows
POJ - 2186
时限: 2000MS 内存: 65536KB 64位IO格式: %I64d & %I64u

 状态

已开启划词翻译

问题描述

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. 

输入

* 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. 

输出

* Line 1: A single integer that is the number of cows who are considered popular by every other cow. 

样例输入

3 3
1 2
2 1
2 3

样例输出

1

提示

Cow 3 is the only cow of high popularity. 

来源



大意:输入n个牛m个有序对,(A,B)表示A认为B是红人。。。。最后求被所有其他牛都认为是红人的牛的个数。

思路:强连通分量的分解,先顺序dfs一次再逆序dfs一次,因为强连通分量2次都是能相互连通的,所以求出了强连通分量(既是都互相认为是红人的)。最后再拓扑排序最后的一个强连通分量里面牛个数就是最后的答案(复杂度O(m+n))代码参考挑战程序设计竞赛

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=50005;
int N,M,V;
int A[maxn],B[maxn];
vector<int> G[maxn];
vector<int> rG[maxn];
vector<int> vs;//后序遍历顺序
bool used[maxn];
int cmp[maxn];//拓扑排序

void add(int f,int t)
{
    G[f].push_back(t);
    rG[t].push_back(f);
}
void dfs(int v)
{
    used[v]=true;
    for(int i=0;i<G[v].size();i++)
    {
        if(!used[G[v][i]]) dfs(G[v][i]);
    }
    vs.push_back(v);
}
void rdfs(int v,int k)
{
    used[v]=true;
    cmp[v]=k;
    for(int i=0;i<rG[v].size();i++)
    {
        if(!used[rG[v][i]]) rdfs(rG[v][i],k);
    }
}
int scc()
{
    memset(used,0,sizeof(used));
    vs.clear();
    for(int v=0;v<V;v++)
    {
        if(!used[v]) dfs(v);
    }
    memset(used,0,sizeof(used));
    int k=0;
    for(int i=vs.size()-1;i>=0;i--)
    {
        if(!used[vs[i]]) rdfs(vs[i],k++);
    }
    return k;
}
int main()
{
    cin>>N>>M;
    V=N;
    for(int i=0;i<M;i++)
    {
        cin>>A[i]>>B[i];
        add(A[i]-1,B[i]-1);
    }
    int n=scc();
    int u=0,num=0;
    for(int v=0;v<V;v++)
    {
        if(cmp[v]==n-1)
        {
            u=v;
            num++;
        }
    }
    memset(used,0,sizeof(used));
    rdfs(u,0);
    for(int v=0;v<V;v++)
    {
        if(!used[v])
        {
            num=0;
            break;
        }
    }
    cout<<num<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值