AcWing 1174. 受欢迎的牛
原题链接
中等
作者:
zqc
,
2021-04-29 16:05:40
,
所有人可见
,
阅读 286
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10, M = 5e4 + 10;
int n, m;
int h[N], e[M], ne[M], idx;
int dnf[N], low[N], timestamp;//时间戳
int stk[N], top;//栈
bool in_stk[N];//是否在栈中
int id[N], scc_cnt;
int psize[N];
int aout[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void tarjin(int u)
{
dnf[u] = low[u] = ++ timestamp;
stk[++ top] = u, in_stk[u] = true;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (!dnf[j])
{
tarjin(j);
low[u] = min(low[u], low[j]);
}
else if (in_stk[j])
low[u] = min(low[u], dnf[j]);
}
if (dnf[u] == low[u])
{
++ scc_cnt;
int y;
do{
y = stk[top --];
in_stk[y] = false;
id[y] = scc_cnt;
psize[scc_cnt] ++;
} while(y != u);
}
}
int main(void)
{
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i ++)
{
int a, b;
cin >> a >>b;
add(a, b);
}
for (int i = 1; i <= n; i ++)
if (!dnf[i])
tarjin(i);
for (int i = 1; i <= n; i ++)
for (int j = h[i]; ~j; j = ne[j])
{
int k = e[j];
int a = id[i], b = id[k];
if (a != b)
{
aout[a] ++;
}
}
int sizep = 0, sum = 0;
for (int i = 1; i <= scc_cnt; i ++)
if (!aout[i])
{
sizep ++;
sum += psize[i];
if (sizep > 1)
{
sum = 0;
break;
}
}
printf("%d\n", sum);
return 0;
}