# BZOJ 1051 || POJ 2186 受欢迎的牛 Tarjan

Description

Input

Output

Sample Input

3 3
1 2
2 1
2 3

Sample Output

1

HINT

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

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
const int MAXN = 50010;
struct Edge
{
int f, t;
}es[MAXN];
int first[MAXN], nxt[MAXN], scc_cnt, sccnum[MAXN], scctong[MAXN], low[MAXN];
stack < int > s;
int n, m, pre[MAXN], dfs_clock, cd[MAXN], tot = 1;
int ff[MAXN], tt[MAXN];

void build(int f, int t)
{
es[++tot].t = t;
nxt[tot] = first[f];
first[f] = tot;
}

void dfs(int u)
{
pre[u] = low[u] = ++dfs_clock;
s.push(u);
for(int i = first[u]; i ; i = nxt[i])
{
int v = es[i].t;
if(!pre[v])
{
dfs(v);
low[u] = min(low[u], low[v]);
}
else if(!sccnum[v])
{
low[u] = min(low[u], pre[v]);
}
}
if(low[u] == pre[u])
{
scc_cnt++;
for(;;)
{
int x = s.top();
s.pop();
sccnum[x] = scc_cnt;
scctong[scc_cnt]++;
if(x == u)
break;
}
}
}

int main()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++)
{
scanf("%d%d", &ff[i], &tt[i]);
build(ff[i], tt[i]);
}
for(int i = 1; i <= n; i++)
if(!pre[i])
dfs(i);
for(int i = 1; i <= m; i++)
{
if(sccnum[ff[i]] != sccnum[tt[i]])
{
cd[sccnum[ff[i]]]++;
}
}
int ans = 0, tot = 0;
for(int i = 1; i <= scc_cnt; i++)
{
if(cd[i] == 0)
{
ans += scctong[i];
tot ++;
}
}
if(tot == 1) printf("%d", ans);
else printf("%d", 0);
return 0;
} 
posted @ 2016-03-26 15:22  Loi_Vampire  阅读(...)  评论(... 编辑 收藏