POJ 2486 Apple Tree ( 樹型DP )

來源:互聯網
上載者:User

標籤:動態規劃   演算法   poj   


#include <iostream>#include <cstring>#include <deque>using namespace std;#define SIZE 230#define BACK 1#define AWAY 0int DP[SIZE][SIZE][2];bool visits[SIZE];int vals[SIZE];deque< int > tree[SIZE];int num, steps;void dfs( int u ){    visits[u] = true;    const int len = tree[u].size();    for( int i = 0; i <= steps; ++i )        DP[u][i][BACK] = DP[u][i][AWAY] = vals[u];    for( int i = 0; i < len; ++i ){        int son = tree[u][i];        if( visits[son] )            continue;        dfs( son );        for( int s = steps; s >= 0; --s ){            for( int ss = 0; ss <= s; ++ss ){                /*                    從 u 出發,回到 u,需要多走兩步 u->son,son->u,                    分配給 son 子樹 ss 步,其他子樹 s - ss 步,都返回.                */                DP[u][s + 2][BACK] = max( DP[u][s + 2][BACK],                                          DP[u][s - ss][BACK] + DP[son][ss][BACK] );                /*                    不回 u (去 u 的其他子樹),在 son 返回.                */                DP[u][s + 2][AWAY] = max( DP[u][s + 2][AWAY],                                          DP[u][s - ss][AWAY] + DP[son][ss][BACK] );                /*                    先遍曆 u 的其他子樹,回到 u 後,遍曆 son 子樹,                    在當前子樹 son 不返回,多走一步.                */                DP[u][s + 1][AWAY] = max( DP[u][s + 1][AWAY],                                          DP[u][s - ss][BACK] + DP[son][ss][AWAY] );            }        }    }}int main(){    int u, v;    while( cin >> num >> steps ){        memset( DP,     0,     sizeof( DP ) );        memset( visits, false, sizeof( visits ) );        for( int i = 1; i <= num; ++i )            tree[i].clear();        for( int i = 1; i <= num; ++i )            cin >> vals[i];        for( int i = 1; i <= num - 1; ++i ){            cin >> u >> v;            tree[u].push_back( v );            tree[v].push_back( u );        }        dfs( 1 );        cout << max( DP[1][steps][BACK], DP[1][steps][AWAY] ) << endl;    }    return 0;}


POJ 2486 Apple Tree ( 樹型DP )

聯繫我們

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