HDU 2196 Computer——树形dp

来源:互联网 发布:端口是什么 怎么查看 编辑:程序博客网 时间:2024/06/05 17:04

需要两遍dfs,一遍向上, 一遍向下

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int INF = 0x3f3f3f3f;const int maxn = 1e4 + 10;int n, tot, head[maxn], dp[maxn][3];void init() {    tot = 0;    memset(head, -1, sizeof(head));}struct Edge {    int to, cost, next;}edge[maxn*2];void addedge(int u, int v, int cost) {    ++tot;    edge[tot].to = v, edge[tot].cost = cost, edge[tot].next = head[u];    head[u] = tot;}void dfs1(int u, int p) {    for (int i = head[u]; i != -1; i = edge[i].next) {        int v = edge[i].to;        if (v != p) dfs1(v, u);    }    int pos = -1;    for (int i = head[u]; i != -1; i = edge[i].next) {        int v = edge[i].to, cost = edge[i].cost;        if (v == p) continue;        if (dp[v][0] + cost > dp[u][0]) {            dp[u][0] = dp[v][0] + cost;            pos = v;        }    }    for (int i = head[u]; i != -1; i = edge[i].next) {        int v = edge[i].to, cost = edge[i].cost;        if (v == p || v == pos) continue;        dp[u][1] = max(dp[u][1], dp[v][0] + cost);    }}void dfs2(int u, int p) {    for (int i = head[u]; i != -1; i = edge[i].next) {        int v = edge[i].to, cost = edge[i].cost;        if (v == p) continue;        dp[v][2] = max(dp[u][2], (dp[v][0] + cost == dp[u][0]) ? dp[u][1] : dp[u][0]) + cost;        dfs2(v, u);    }}int main() {    while (~scanf("%d", &n)) {        init();        int v, cost;        for (int i = 2; i <= n; i++) {            scanf("%d %d", &v, &cost);            addedge(i, v, cost); addedge(v, i, cost);        }        memset(dp, 0, sizeof(dp));        dfs1(1, -1);        dfs2(1, -1);        for (int i = 1; i <= n; i++) {            printf("%d\n", max(dp[i][0], dp[i][2]));        }    }    return 0;}


原创粉丝点击