Popular Cows (强连通分量)

在一组牛群中,每头牛都梦想成为最受欢迎的牛。给定每头牛对其他牛的流行度看法,任务是找出被所有牛都认为受欢迎的牛的数量。流行度具有传递性,如果A认为B受欢迎,B认为C受欢迎,那么A也会认为C受欢迎。输入包含牛的数量N和关系对M,输出是全牛群中被视为普遍受欢迎的牛的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. 

 

【题意】

 

【思路】

 

【代码】

#include <iostream>
#include <algorithm>
#include <cstring>
#include<vector>
using namespace std;

const int maxn=1e5+10;
vector<int> G[maxn];//图的邻接表表示
vector<int> rG[maxn];//把边反向后的图
vector<int> vs;//后序遍历顺序的顶点列表
bool used[maxn];//访问标记
int cmp[maxn];//所属强连通分量的拓扑序
int a[maxn],b[maxn];
int V,N,M;

void add_edge(int from,int to)
{
    G[from].push_back(to);
    rG[to].push_back(from);
}

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_edge(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;
}

 

*强连通分量(模板)

ps:

参考书:挑战程序设计竞赛(第2版)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值