演算法:poj 1155 TELE (樹形背包dp)

來源:互聯網
上載者:User

題意

某收費有線電視網計劃轉播一場重要的足球比賽。他們的轉播網和使用者終端構成一棵樹狀結 構,這棵樹的根結點位於足球比賽的現場,樹葉為各個使用者終端,其他中轉站為該樹的內部節點。

從 轉播站到轉播站以及從轉播站到所有使用者終端的訊號傳輸費用都是已知的,一場轉播的總費用等於傳輸訊號 的費用總和。

現在每個使用者都準備了一筆費用想觀看這場精彩的足球比賽,有線電視網有權決定給哪 些使用者提供訊號而不給哪些使用者提供訊號。

寫一個程式找出一個方案使得有線電視網在不虧本的情況 下使觀看轉播的使用者儘可能多。

思路

樹形背包的入門題。

f(i, j),表示子樹i轉播給j個使用者 的最大收益值

這題可以看作是樹上的分組背包,每個子樹看作是一組物品,這一組物品可以取1個,2 個...j個

然後就是套用分組背包的演算法了

f(i, 1) = w(i), 當點i是葉子節點時

f(i, j) = max{ f(i, j-k) + f[v][k] - w(i, v) | v是i的兒子節點, 0<=k<=j}

代碼

/**=====================================================* This is a solution for ACM/ICPC problem** @source:poj-1155 TELE* @type: 樹形背包dp* @author: shuangde* @blog: blog.csdn.net/shuangde800* @email: zengshuangde@gmail.com* Copyright (C) 2013/08/18 19:29 All rights reserved.*======================================================*/#include <iostream>#include <cstdio>#include <algorithm>#include <vector>#include <queue>#include <cmath>#include <cstring>#define MP make_pairusing namespace std;    typedef pair<int, int >PII;typedef long long int64;const int INF = 0x3f3f3f3f;const double PI = acos(-1.0);    const int MAXN = 3010;    namespace Adj{int size, head[MAXN];struct Node {int v, next, w; }E[MAXN];void initAdj() { size = 0; memset(head, -1, sizeof(head)); }void addEdge(int u, int v, int w) {E[size].v = v;E[size].w = w;E[size].next = head[u];head[u] = size++;}}using namespace Adj;/////////////////////////////    int n, m;int val[MAXN];int f[MAXN][MAXN];    // 返回的是有幾個葉子節點int dfs(int u) {// initfor (int i = 1; i <= m; ++i)f[u][i] = -INF;    if (head[u] == -1) {f[u][1] = val[u];return 1;}    int sum = 0;for (int e = head[u]; e != -1; e = E[e].next) {int v = E[e].v, w = E[e].w;    int numLeaf = dfs(v);sum += numLeaf;// 做分組背包// http://www.bianceng.cnfor (int s = sum; s >= 1; --s) {for (int k = 0; k <= numLeaf && k <= s; ++k)f[u][s] = max(f[u][s], f[u][s-k] + f[v][k] + w);}}return sum;}    int main(){    while (~scanf("%d%d", &n, &m)) {initAdj();for (int i = 1; i <= n - m; ++i) {int x, v, w;scanf("%d", &x);while (x--) {scanf("%d%d", &v, &w);addEdge(i, v, -w);}}    for (int i = n - m + 1; i <= n; ++i) {scanf("%d", &val[i]);}dfs(1);for (int i = m; i >= 0; --i) {if (f[1][i] >= 0) {printf("%d\n", i);break;}}}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.