dp專輯 A – Rebuilding Roads [ 樹形dp]

來源:互聯網
上載者:User

第二道樹形dp的題,看別人的代碼,看了一下午才明白,還沒入門呀~

題意:

有n個點組成一棵樹,問至少要刪除多少條邊才能獲得一棵有p個結點的子樹?


思路:

設dp[i][k]為以i為根,產生節點數為k的子樹,所需剪掉的邊數。

dp[i][1] = total(i.son) + 1,即剪掉與所有兒子(total(i.son))的邊,還要剪掉與其父親(+1)的邊。

dp[i][k] = min(dp[i][k],dp[i][j - k] + dp[i.son][k] - 2),即由i.son產生一個節點數為k的子樹,再由i產生其他j-k個節點數的子樹。

這裡要還原i與i.son和其父親的邊所以-2。

參考大牛的代碼~  一開始

dp[root][j] = min(dp[root][j], dp[root][j - k] + dp[tree[root][i]][k] - 2);

中的-2,始終想不明白,不是-1就可以了嗎?在這裡糾結了好久,後來結合

for (int i = 1; i <= n; i++)    {//為以i為根,產生節點數為1的子樹所需剪掉的邊數  每個結點都有個父結點 +1  根結點有個虛擬父結點,方便統一處理        dp[i][1] = tree[i].size() + 1;        for (int j = 2; j <= p; j++)            dp[i][j] = MAX;    }
dp[root][p]--;

才明白了,頓感大牛們智商太高了,膜拜一會兒~後來仔細想想,這樣也是為了方便處理問題~


//AC CODE:


#include<iostream>#include<cmath>#include<algorithm>#include<vector>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>using namespace std;const int MAX = 10000;vector <int> tree[160];//設dp[i][k]為以i為根,產生節點數為k的子樹  所需 剪掉 的 邊數int a, b, n, p, dp[160][160];bool son[160];void dfs(int root){    int len=tree[root].size();    for (int i = 0; i < len; i++)    {        dfs(tree[root][i]);//遞迴調用孩子結點(後根遍曆)        for (int j = p; j > 1; j--)//j==1 的情況已經存在 >1 即可            for (int k = 1; k < j; k++)                dp[root][j] = min(dp[root][j], dp[root][j - k] + dp[tree[root][i]][k] - 2);    }}int main(){    scanf("%d %d",&n,&p);    memset(son, false, sizeof(son));    for (int i = 0; i < n - 1; i++)    {        scanf("%d %d",&a,&b);        tree[a].push_back(b);        son[b] = true;//記錄b是否有兒子    }    int root = 1;    while(son[root])//找父結點        root++;    for (int i = 1; i <= n; i++)    {//為以i為根,產生節點數為1的子樹所需剪掉的邊數  每個結點都有個父結點 +1  根結點有個虛擬父結點,方便統一處理        dp[i][1] = tree[i].size() + 1;        for (int j = 2; j <= p; j++)            dp[i][j] = MAX;    }    dfs(root);    dp[root][p]--;// 與dp方程中+2有關,還原i與其父親的邊,最後i為父節點,則-1    int ans = MAX;    for (int i = 1; i <= n; i++)        ans = min(ans, dp[i][p]);    printf("%d\n",ans);    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.