POJ 2186

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 31241 Accepted: 12691

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

这道题就是把强连通分量分解,然后取出最末尾的那个分量看是否成立即可

#include<iostream>
#include<vector>
using namespace std;
const long max_v=10005;
vector<long>G[max_v];
vector<long>rG[max_v];
vector<long>vs;
long v,cmp[max_v],n,m;
bool used[max_v];
void add_edge(long from,long to)
{
    G[from].push_back(to);
    rG[to].push_back(from);
}
void dfs(long v)
{
    used[v]=1;
    for(long i=0;i<G[v].size();i++)
        if(!used[G[v][i]])dfs(G[v][i]);
    vs.push_back(v);
}
void rdfs(long v,long k)
{
    used[v]=1;
    cmp[v]=k;
    for(long i=0;i<rG[v].size();i++)
        if(!used[rG[v][i]])rdfs(rG[v][i],k);
}
long scc()
{
    memset(used,0,sizeof(used));
    vs.clear();
    for(long v=0;v<n;v++)
        if(!used[v])dfs(v);
    memset(used,0,sizeof(used));
    long k=0;
    for(long i=vs.size()-1;i>=0;i--)
        if(!used[vs[i]])rdfs(vs[i],k++);
    return k;
}
int main()
{
    cin>>n>>m;
    for(long i=0;i<m;i++)
    {
        long f,t;
        cin>>f>>t;
        add_edge(f-1,t-1);
    }
    long x=scc(),ans=0,v;
//    cout<<x<<endl;
    for(long i=0;i<n;i++)
        if(cmp[i]==x-1){ans++;v=i;}
    memset(used,0,sizeof(used));
    rdfs(v,0);
    bool f=true;
    for(long i=0;i<n;i++)
        if(!used[i]){f=false;break;}
    if(f)cout<<ans<<endl;else cout<<0<<endl;
//    system("pause");
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值