演算法:ural 1018 Binary Apple Tree(樹形dp | 經典)

來源:互聯網
上載者:User

題意

給一棵邊有權值的二叉樹,節點編號為1~n,1是根節點。求砍掉一些邊,只保留q條邊,這q條邊 構成的子樹

的根節點要求是1,問這顆子樹的最大權值是多少?

思路

非常經典的一道樹形dp題 ,根據我目前做過的題來看,有多道都是由這題衍生出來的。

f(i, j) 表示子樹i,保留j個節點(注意是 節點)的最大權值。每條邊的權值,把它看作是串連的兩個節點中的兒子節點的權值。

那麼,就可以對所 有i的子樹做分組背包,即每個子樹可以選擇1,2,...j-1條邊分配給它。

狀態轉移為:

f(i, j) = max{ max{f(i, j-k) + f(v, k) | 1<=k<j} | v是i的兒子}

ans = f(1, q+1)

代碼

/**=====================================================* This is a solution for ACM/ICPC problem** @source : ural-1018 Binary Apple Tree* @description : 樹形dp* @author : shuangde* @blog : blog.csdn.net/shuangde800* @email : zengshuangde@gmail.com* Copyright (C) 2013/09/01 18:43 All rights reserved.*======================================================*/#include <iostream>#include <cstdio>#include <algorithm>#include <vector>#include <cstring>#define MP make_pairusing namespace std;    typedef pair<int, int>PII;typedef long long int64;const int INF = 0x3f3f3f3f;    const int MAXN = 110;vector<PII>adj[MAXN];int n, q;int tot[MAXN];int f[MAXN][MAXN];// http://www.bianceng.cn    int dfs(int u, int fa) {tot[u] = 1;for (int e = 0; e < adj[u].size(); ++e) {int v = adj[u][e].first;if (v == fa) continue;tot[u] += dfs(v, u);}    for (int e = 0; e < adj[u].size(); ++e) {int v = adj[u][e].first;int w = adj[u][e].second;if (v == fa) continue;for (int i = tot[u]; i > 0; --i) {for (int j = 1; j < i && j <= tot[v]; ++j) {f[u][i] = max(f[u][i], f[u][i-j] + f[v][j] + w);}}}return tot[u];}    int main(){    while (~scanf("%d%d", &n, &q)) {    for (int i = 0; i <= n; ++i)adj[i].clear();    for (int i = 0; i < n - 1; ++i) {int u, v, w;scanf("%d%d%d", &u, &v, &w);adj[u].push_back(MP(v, w));adj[v].push_back(MP(u, w));}memset(f, 0, sizeof(f));dfs(1, -1);printf("%d\n", f[1][q+1]);}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.