紫書動規 P282的問題 hdu2196 樹形dp

題目鏈接:

http://acm.hdu.edu.cn/showproblem.php?pid=2196

題意:

題解:

http://blog.csdn.net/shuangde800/article/details/9732825
f[i][0],表示頂點爲i的子樹的,距頂點i的最長距離
f[i][1],表示Tree(i的父節點)-Tree(i)的最長距離+i跟i的父節點距離

要求所有的f[i][0]很簡單,只要先做一次dfs求每個結點到葉子結點的最長距離即可。
然後要求f[i][1], 可以從父節點遞推到子節點

代碼:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;

struct node{
    int v,w;
};
vector<node> g[maxn];
int vis[maxn],f[maxn][2];

int dfs1(int u){
    vis[u] = 1;
    f[u][0] = 0;
    for(int i=0; i<(int)g[u].size(); i++){
        int v = g[u][i].v, w = g[u][i].w;
        if(vis[v]) continue;
        f[u][0] = max(f[u][0],dfs1(v)+w);
    }
    return f[u][0];
}



void dfs2(int u){
    vis[u] = 1;
    int max1=0,max2=0,v1,v2;

    for(int i=0; i<(int)g[u].size(); i++){
        int v = g[u][i].v, w = g[u][i].w;
        if(vis[v]) continue; // 不能返回到父節點

        int tmp = f[v][0]+w;
        if(tmp > max1){
            max2 = max1; v2 = v1;
            max1 = tmp; v1 = v;
        }else if(tmp > max2){
            max2 = tmp; v2 = v;
        }
    }

    if(u != 1){
        int tmp = f[u][1];
        int v = -1;
        if(tmp > max1){
            max2 = max1; v2 = v1;
            max1 = tmp; v1 = v;
        }else if(tmp > max2){
            max2 = tmp; v2 = v;
        }
    }

    for(int i=0; i<(int)g[u].size(); i++){
        int v = g[u][i].v, w = g[u][i].w;
        if(vis[v]) continue;
        if(v == v1)
            f[v][1] = max2 + w;
        else
            f[v][1] = max1 + w;
        // cout << v << " " << f[v][1] << endl;
        dfs2(v);
    }

}

int main(){
    int n;
    while(scanf("%d",&n) == 1){
        for(int i=0; i<=n; i++) g[i].clear();
        for(int i=2; i<=n; i++){
            int v,w; cin >> v >> w;
            g[i].push_back(node{v,w});
            g[v].push_back(node{i,w});
        }
        MS(f);
        MS(vis);
        dfs1(1);
        MS(vis);
        dfs2(1);

        for(int i=1; i<=n; i++)
            cout << max(f[i][0],f[i][1]) << endl;
    }



    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章