#include<iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int* ingred = new int[n + 1];
int* head = new int[n + 1];
int* to = new int[m + 1];
int* w = new int[n + 1];
int* queue = new int[m + 1];
int* next = new int[m + 1];
int* ou = new int[n + 1];
int l = 0, r = 0;
for (int i = 0; i <= n; i++) {
head[i] = -1;
ingred[i] = 0;
w[i] = 0;
ou[i] = 0;
}
int a, b;
for (int i = 1; i <= m; i++) {
cin >> a >> b;
to[i] = b;
ingred[b]++;
ou[a]++;
next[i] = head[a];
head[a] = i;
}
for (int i = 1; i <= n; i++) {
if (ingred[i] == 0&&ou!=0) {
w[i] = 1;
queue[r++] = i;
}
int ans = 0;
while (l < r) {
if (head[queue[l]] == -1) {
ans += w[queue[l]];
}
else {
for (int ei = head[queue[l]]; ei > 0; ei = next[ei]) {
if (--ingred[to[ei]] == 0) {
queue[r++] = to[ei];
}
w[to[ei]] += w[queue[l]];
}
}
l++;
}
cout << ans << endl;
return 0;
}
}
求助