同 AcWing 1174 受欢迎的牛
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using p = pair<int, int>;
const int maxn(1e4 + 10);
const int maxm(5e4 + 10);
int ecnt, head[maxn];
int tim, dfn[maxn], low[maxn];
int scnt, scc[maxn], siz[maxn], deg[maxn];
bool vis[maxn];
stack<int> st;
struct edge {
int to, nxt;
} edges[maxm];
template<typename T = int>
inline const T read()
{
T 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 << 3) + (x << 1) + ch - '0';
ch = getchar();
}
return x * f;
}
template<typename T>
inline void write(T x, bool ln)
{
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) write(x / 10, false);
putchar(x % 10 + '0');
if (ln) putchar(10);
}
void addEdge(int u, int v)
{
edges[ecnt].to = v;
edges[ecnt].nxt = head[u];
head[u] = ecnt++;
}
void tarjan(int u)
{
dfn[u] = low[u] = ++tim;
st.push(u);
vis[u] = true;
for (int i = head[u]; compl i; i = edges[i].nxt) {
int v = edges[i].to;
if (not dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (vis[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (dfn[u] == low[u]) {
++scnt;
int v = 0;
do {
v = st.top();
st.pop();
vis[v] = false;
scc[v] = scnt;
++siz[scnt];
} while (v not_eq u);
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("input.txt", "r", stdin);
#endif
ios::sync_with_stdio(false);
memset(head, -1, sizeof head);
int n = read(), m = read();
while (m--) {
int u = read(), v = read();
addEdge(u, v);
}
for (int i = 1; i <= n; ++i) {
if (not dfn[i]) {
tarjan(i);
}
}
for (int u = 1; u <= n; ++u) {
for (int i = head[u]; compl i; i = edges[i].nxt) {
int v = edges[i].to;
int a = scc[u], b = scc[v];
if (a not_eq b) {
++deg[a];
}
}
}
int cnt = 0, sum = 0;
for (int i = 1; i <= scnt; ++i) {
if (not deg[i]) {
++cnt;
sum += siz[i];
if (cnt > 1) {
sum = 0;
break;
}
}
}
write(sum, true);
return 0;
}