zoukankan      html  css  js  c++  java
  • hdu2196

    基本的树形dp,需要dfs三次,第一次求每个点最远的后代,第二次和第三次每个点的孩子分别从左到右和从右到左遍历。

    #include <cstdio>
    #include <vector>
    using namespace std;
    
    #define D(x) 
    
    const int MAX_N = (int)(1e4) + 5;
    
    int n;
    vector <pair<int, int> > edge[MAX_N];
    int child[MAX_N];
    int father_left[MAX_N];
    int father_right[MAX_N];
    
    void dfs_child(int father, int u)
    {
        child[u] = 0;
        for (int i = 0; i < (int)edge[u].size(); i++)
        {
            int v = edge[u][i].first;
            int w = edge[u][i].second;
            if (v != father)
            {
                dfs_child(u, v);
                child[u] = max(child[u], child[v] + w);
            }
        }
    }
    
    void dfs_father_left(int father, int u, int up)
    {
        father_left[u] = up;
        int temp = 0;
        for (int i = 0; i < (int)edge[u].size(); i++)
        {
            int v = edge[u][i].first;
            int w = edge[u][i].second;
            if (v != father)
            {
                dfs_father_left(u, v, max(up, temp) + w);
                temp = max(temp, w + child[v]);
            }
        }
    }
    
    void dfs_father_right(int father, int u, int up)
    {
        father_right[u] = up;
        int temp = 0;
        for (int i = (int)edge[u].size() - 1; i >= 0; i--)
        {
            int v = edge[u][i].first;
            int w = edge[u][i].second;
            if (v != father)
            {
                dfs_father_right(u, v, max(up, temp) + w);
                temp = max(temp, w + child[v]);
            }
        }
    }
    
    int main()
    {
        while (scanf("%d", &n) != EOF)
        {
            for (int i = 1; i <= n; i++)
            {
                edge[i].clear();
            }
            for (int i = 2; i <= n; i++)
            {
                int a, b;
                scanf("%d%d", &a, &b);
                edge[i].push_back(make_pair(a, b));
                edge[a].push_back(make_pair(i, b));
            }
            dfs_child(-1, 1);
            dfs_father_left(-1, 1, 0);
            dfs_father_right(-1, 1, 0);
            for (int i = 1; i <= n; i++)
            {
                D(printf("%d %d %d
    ", child[i], father_left[i], father_right[i]));
                printf("%d
    ", max(child[i], max(father_left[i], father_right[i])));
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    cocos2d多语言互调之一---lua调java
    vue 组件
    封装 XMLHttpRequest
    Ajax 请求
    jq 显示和隐藏 计时器
    jq 动画DOM及其操作
    jq 表单提交
    jq 事件绑定
    js 一些实用的封装和兼容
    工厂、原型、混合模式
  • 原文地址:https://www.cnblogs.com/rainydays/p/4382026.html
Copyright © 2011-2022 走看看