第二道樹形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;}