BZOJ1051: [HAOI2006]受欢迎的牛

Description

  每一头牛的愿望就是变成一头最受欢迎的牛。现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎。 这
种关系是具有传递性的,如果A认为B受欢迎,B认为C受欢迎,那么牛A也认为牛C受欢迎。你的任务是求出有多少头
牛被所有的牛认为是受欢迎的。
Input

  第一行两个数N,M。 接下来M行,每行两个数A,B,意思是A认为B是受欢迎的(给出的信息有可能重复,即有可
能出现多个A,B)
Output

  一个数,即有多少头牛被所有的牛认为是受欢迎的。

Sample Input

3 3

1 2

2 1

2 3
Sample Output

1
HINT

100%的数据N<=10000,M<=50000


solution

tarjan缩点

#include <stack>
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

#define N 50000
#define M N<<2

int nxt[M], to[M], nxt_[M], to_[M], head[N], head_[N];
int cnt = 0, cnt_ = 0;
int tot = 0, tot_ = 0;
int DFN[N], LOW[N];
int belong[N], ann[N];
stack<int> sta;
bool vis[N];

void addeage( int u, int v ){
    nxt[++cnt] = head[u], to[cnt] = v, head[u] = cnt;
}

void addeage_( int u, int v ){
    nxt_[++cnt_] = head_[u], to_[cnt_] = v, head_[u] = cnt_;
}

void tarjan( int x ){
    sta.push(x);
    vis[x] = true;
    DFN[x] = LOW[x] = ++tot;
    for ( int i = head[x]; i; i = nxt[i] ){
        int v = to[i];
        if ( !DFN[v] ){
            tarjan( v );
            LOW[x] = min( LOW[v], LOW[x] );
        }
        else if ( vis[v] ){
            LOW[x] = min( LOW[x], DFN[v] );
        }
    }
    if ( LOW[x] == DFN[x] ){
        tot_ ++;
        int t;
        do{
            t = sta.top();
            vis[t] = false;
            belong[t] = tot_;
            ann[tot_]++;
            sta.pop();
        }while ( x != t );
    }
}

int main(){
    int n, m, a, b;
    scanf( "%d%d", &n, &m);
    for ( int i = 1; i <= m; i++){
        scanf( "%d%d", &a, &b );
        addeage( a, b );
    }
    for ( int i = 1; i <= n; i++)
        if ( !DFN[i]) tarjan( i );
    for ( int i = 1; i <= n; i++)
        for ( int j = head[i]; j; j = nxt[j] ){
            int v = to[j];
            if ( belong[v] != belong[i] ) addeage_( belong[i], belong[v]);
         }
    int ans1 = 0;
    for ( int i = 1; i <= tot_; i++)
        if ( !head_[i] )
            if ( ans1 ) {
                ans1 = 0; break;
            }
            else ans1 = ann[i];
    printf("%d",ans1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值