POJ–1947[Rebuilding Roads] 樹形DP

來源:互聯網
上載者:User

題意:

給你一棵樹,讓你求最少剪掉多少條邊可以剪出一棵邊數為p的子樹.

 

思路:(樹形DP)

(1):f[i][j]:表示以i為根(包含i),共j個節點需要切斷的路的數量
(2):f[i][j+k]=min(f[i][j+k],f[i.son[t]][k])(t為i的孩子)

 

 

CODE:

/*AC代碼:0ms*/#include <iostream>#include <cstdio>#include <memory.h>#include <algorithm>#include <vector>#define MAXN 155#define INF 1e8#define min(a,b) (a<b?a:b)using namespace std;int f[MAXN][MAXN];int N,P;vector<int>Tree[MAXN];void Init(){int i,j,u,v;for(i=0;i<=N;i++)Tree[i].clear();for(i=1;i<N;i++){scanf("%d%d",&u,&v);Tree[u].push_back(v);}for(i=1;i<=N;i++){for(j=1;j<=N;j++)f[i][j]=INF;}}void DFS(int root){int i,j,k;int size=Tree[root].size();for(i=0;i<size;i++)DFS(Tree[root][i]);f[root][1]=size;//類似背包:一顆顆把支添加上去for(i=0;i<size;i++){for(k=P-1;k>=1;k--){if(f[root][k]<INF){for(j=1;j<=P-1&&j+k<=P;j++){if(f[Tree[root][i]][j]<INF)f[root][k+j]=min(f[root][k+j],f[root][k]+f[Tree[root][i]][j]-1);}}}}}void Solve(){int i,res;res=INF;DFS(1);for(i=2;i<=N;i++){res=min(res,f[i][P]+1);}res=min(res,f[1][P]);printf("%d\n",res);}int main(){while(scanf("%d%d",&N,&P)!=EOF){Init();Solve();}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.