您的位置:首页 > 其它

【bzoj1051】 [HAOI2006]受欢迎的牛 tarjan缩点判出度算点数

2015-08-14 17:45 344 查看

【bzoj1051】 [HAOI2006]受欢迎的牛

2014年1月8日7450

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【数据范围】
10%的数据N<=20, M<=50
30%的数据N<=1000,M<=20000
70%的数据N<=5000,M<=50000
100%的数据N<=10000,M<=50000

代码

#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <queue>
#include <typeinfo>
#include <map>
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
#define inf 10000000
inline ll read()
{
ll x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
//***************************************************************
int head[10001],dfn[10001];
struct ss
{
int to,next;
int hea;
} e[10001*5];
int t=1;
int bcnt;
int cnt;
int belong[10001];
int hav[10001];
int out[10001];
int n,m,top,low[10001],stacks[10001];
int vis[10001];
int instack[10001];
void add(int u,int v)
{
e[t].hea=u;
e[t].to=v;
e[t].next=head[u];
head[u]=t++;
}
void dfs(int u)
{
dfn[u]=low[u]=++cnt;
stacks[++top]=u;
instack[u]=1;
vis[u]=1;
for(int i=head[u];i;i=e[i].next){
if(!vis[e[i].to]){
dfs(e[i].to);
low[u]=min(low[u],low[e[i].to]);
}
else if(instack[u]){low[u]=min(low[u],dfn[e[i].to]);}
}
int v=-1;
if(low[u]==dfn[u]){
bcnt++;
while(u!=v){
v=stacks[top--];
instack[v]=0;
belong[v]=bcnt;
hav[bcnt]++;
//vis[v]=0;
}
}
}
void rebuild(){
for(int i=1;i<=m;i++){
if(belong[e[i].hea]!=belong[e[i].to])
out[belong[e[i].hea]]++;
}
}
void tarjan(){

for(int i=1;i<=n;i++){
if(!vis[i])dfs(i);
}
rebuild();
}
void work()
{
int res=0,ans;
//cout<<bcnt<<endl;
for(int i=1;i<=bcnt;i++){
if(out[i]==0)
{
res++;
ans=i;
}
/// printf("%d\n",hav[i]);
}
if(res==1){
printf("%d\n",hav[ans]);
}
else printf("0\n");
}
int main()
{

scanf("%d%d",&n,&m);
int a,b;
for(int i=1; i<=m; i++)
{
scanf("%d%d",&a,&b);
add(a,b);
}
tarjan();
work();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: