UVa 1407 樹形背包 Caves

來源:互聯網
上載者:User

標籤:

這道題可以和POJ 2486 樹形背包DP Apple Tree比較著來做。

參考題解

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <vector> 6 using namespace std; 7  8 const int maxn = 500 + 10; 9 10 int n, Q;11 vector<int> G[maxn], C[maxn];12 13 int d[maxn][maxn][2], cnt[maxn];14 15 void dfs(int u)16 {17     cnt[u] = 1;18     d[u][1][0] = d[u][1][1] = 0;19     for(int i = 0; i < G[u].size(); i++)20     {21         int v = G[u][i];22         int w = C[u][i];23         dfs(v);24         cnt[u] += cnt[v];25 26         for(int j = cnt[u]; j >= 2; j--)27             for(int x = 0; x <= j && x <= cnt[v]; x++)28             {29                 d[u][j][0] = min(d[u][j][0], d[v][x][0] + d[u][j-x][0] + w * 2);30                 d[u][j][1] = min(d[u][j][1], d[v][x][0] + d[u][j-x][1] + w * 2);31                 d[u][j][1] = min(d[u][j][1], d[v][x][1] + d[u][j-x][0] + w);32             }33     }34 }35 36 int main()37 {38     int kase = 1;39     while(scanf("%d", &n) == 1 && n)40     {41         for(int i = 0; i < n; i++) { G[i].clear(); C[i].clear(); }42         for(int i = 1; i < n; i++)43         {44             int a, b, d; scanf("%d%d%d", &a, &b, &d);45             G[b].push_back(a); C[b].push_back(d);46         }47 48         memset(d, 0x3f, sizeof(d));49         dfs(0);50 51         printf("Case %d:\n", kase++);52         scanf("%d", &Q);53         while(Q--)54         {55             int x; scanf("%d", &x);56             int ans;57             for(ans = n; ans > 0; ans--) if(d[0][ans][1] <= x) break;58             printf("%d\n", ans);59         }60     }61 62     return 0;63 }
代碼君

 

UVa 1407 樹形背包 Caves

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.