題目鏈接
題目描述
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
題解
先構圖,如果不連通直接輸出0。
我們用tarjan將強連通分量縮成一個點,這樣就得到了一個有向無環圖。所有出度爲0的點所代表的的強連通分量的大小就是答案。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;
#define N 10010
int dfn[N],low[N],t[N],size[N],p[N],first[N];
int tot,n,m,x,y,cnt,top,num,ans;
bool f[N],v[N];
struct edge{
int x,next,from;
}e[N*5];
void count(int x){
size[++num]=1;
while(t[top]!=x){
p[t[top]]=num;
f[t[top]]=false;
size[num]++;
top--;
}
p[x]=num; f[x]=false;
top--;
}
void tarjan(int x){
v[x]=f[x]=true;
dfn[x]=low[x]=++cnt;
t[++top]=x;
for(int i=first[x];i;i=e[i].next)
if(!v[e[i].x]){
tarjan(e[i].x);
low[x]=min(low[x],low[e[i].x]);
}
else if(f[e[i].x]) low[x]=min(low[x],low[e[i].x]);
if(dfn[x]==low[x]) count(x);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++){
scanf("%d%d",&x,&y);
e[++tot].x=y;
e[tot].next=first[x];
e[tot].from=x;
first[x]=tot;
}
tarjan(1);
for(int i=1;i<=tot;i++)
if(p[e[i].x]!=p[e[i].from])
f[p[e[i].from]]=true;
for(int i=1;i<=num;i++)
if(!f[i]) ans+=size[i];
printf("%d\n",ans);
return 0;
}