P3916 图的遍历

一个节点的解,即其所有子节点解的最大值,所以一开始想要dfs+记忆化,交上去发现完全不对,因为没有说数据里没有环.

由于我太弱,没有想到如何dfs带环图.


对于一个节点,可以对其所有父节点的解进行更新,使其不小于该节点编号.

故此,编号为N的节点的父节点,及其父节点的父节点,以此类推,解必为N.

更新这些节点后,对于编号为N-1的节点,遍历其尚未被遍历过的父节点,及其父节点的父节点,解必为N-1.

从N号节点一直处理到1号节点即得每个节点的解.

所以有了反向建图方法.

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;

int n, m;
vector<int> s[100010];
int ans[100010];

void dfs(int x, int k) {
    if (ans[x]) return;
    ans[x] = k;
    for(auto i: s[x]) dfs(i, k);
}

int main() {
    cin >> n >> m;
    while(m--) {
        int x, y;
        cin >> x >> y;
        s[y].push_back(x);
    }

    for (int i = n; i >= 1; i--) dfs(i, i);
    for (int i = 1; i <= n; i++) cout << ans[i] << ' ';

    return 0;
}
P3916
原文地址:https://www.cnblogs.com/Gaomez/p/14391787.html