AcWing 2716. 食物链
原题链接
中等
作者:
王小强
,
2021-02-24 12:10:28
,
所有人可见
,
阅读 379
Topologic Sorting Algorithm 我好像悟了!
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, m, u, v;
int main(void) {
scanf("%d %d", &n, &m);
// build the directed graph
vector<vector<int>> g(n + 1);
vector<int> indegrees(n + 1); // 入度表
vector<int> paths(n + 1);
while (m--) {
scanf("%d %d", &u, &v);
++indegrees[v];
g[u].emplace_back(v);
}
queue<int> q;
for (int i = 1; i <= n; ++i)
if (!indegrees[i]) paths[i] = 1, q.emplace(i);
int ans = 0;
while (not q.empty()) {
const int cur = q.front(); q.pop();
for (const auto& nei : g[cur]) {
paths[nei] += paths[cur];
if (--indegrees[nei] == 0) {
q.emplace(nei);
if (g[nei].empty()) ans += paths[nei];
}
}
}
printf("%d\n", ans);
}