bzoj1051: [HAOI2006]受欢迎的牛

来源:互联网 发布:java类库是什么 编辑:程序博客网 时间:2024/05/18 20:09

题目链接

bzoj1051

题目描述

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 10010int 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;}
0 0
原创粉丝点击