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);
}