poj2186 - Popular Cows - 强连通分量

Popular Cows

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 41551 Accepted: 16871

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.

思路:

求被其他所有牛认为是红牛的牛的总数。若是暴力的话,复杂度为O(M*N),肯定超时,这时,我们要换种方法。

求出图的强连通分量,若是一头牛被认为是红牛,那么其所属的强连通分量里的牛都是红牛。

将图进行强连通分量分解后,可发现,只有最后一个强连通分量才有可能是被所有牛都认可。

那么我们对最后一个强连通分量,用rdfs函数走一趟,若有vis==0的点(不能到达该强连通分量,则没有牛是红牛)

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef pair<int,int>P;
const int INF=0x3f3f3f3f;
const int N=10010,mod=32767;
int vis[N];
vector<int>G[N],rG[N];
vector<int>vs;
int cmp[N],n;
void add(int from,int to){
    G[from].push_back(to);
    rG[to].push_back(from);
}

void dfs(int v){
    vis[v]=1;
    for(int i=0;i<G[v].size();i++){
        if(!vis[G[v][i]])dfs(G[v][i]);
    }
    vs.push_back(v);
}
void rdfs(int v,int k){
    vis[v]=1;
    cmp[v]=k;
    for(int i=0;i<rG[v].size();i++){
        if(!vis[rG[v][i]])rdfs(rG[v][i],k);
    }
}
int scc(){
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++){
        if(!vis[i])dfs(i);
    }
    int k=0;
    memset(vis,0,sizeof(vis));
    for(int i=vs.size()-1;i>=0;i--){
        if(!vis[vs[i]])rdfs(vs[i],k++);
    }
    return k;
}

int main(){
    int m,a,b;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        scanf("%d%d",&a,&b);
        add(a,b);
    }
    int k=scc();
    int u=0,num=0;
    for(int i=1;i<=n;i++){
        if(cmp[i]==k-1){
            u=i;
            num++;
        }
    }
    memset(vis,0,sizeof(vis));
    rdfs(u,0);
    for(int i=1;i<=n;i++){
        if(!vis[i]){
            num=0;
            break;
        }
    }
    printf("%d\n",num);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值