洛谷P3916 图的遍历(反向建边+dfs)
题目导航:https://www.luogu.com.cn/problem/P3916
`unordered_map<int, vector
int rr[100010];
int ans[100010]; int allnum; int sn;
void dfs(int x) {
rr[x] = 1; ans[x] = sn;
if (mp[x].empty()) {
return;
}
for (auto y : mp[x]) {
if (!rr[y]) {
ans[y] = sn; allnum--;
dfs(y);
}
}
}
int main() {
int N, M; cin >> N >> M; allnum = N;
for (int i = 0; i < M; i++) {
int U, V; cin >> U >> V;
mp[V].push_back(U);
}
for (int j = N;; j--) {
if (allnum == 0) {
break;
}
if (!rr[j]) {
allnum--; sn = j;
dfs(j);
}
}
for (int i = 1; i <= N; i++) {
cout << ans[i] << " ";
}
return 0;
}`
求每个点可以达到的最大节点,本来打算从根节点开始dfs的,每次迭代返回当前的最大值,但是后来发现并非是边数<节点数的树形,而是有向图,所以根节点出发不太妥当(根本就没有根)
那么只能考虑遍历所有节点,但是一定超时。所以考虑逆着来。

浙公网安备 33010602011771号