poj 1947 Rebuilding Roads(樹形DP)

來源:互聯網
上載者:User

Rebuilding Roads
Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 8227   Accepted: 3672

The cows have reconstructed Farmer John's farm, with its N barns (1 <= N <= 150, number 1..N) after the terrible earthquake last May. The cows didn't have time to rebuild any extra roads, so now there is exactly one way to get from any given barn to any other barn. Thus, the farm transportation system can be represented as a tree. 

Farmer John wants to know how much damage another earthquake could do. He wants to know the minimum number of roads whose destruction would isolate a subtree of exactly P (1 <= P <= N) barns from the rest of the barns.

* Line 1: Two integers, N and P 

* Lines 2..N: N-1 lines, each with two integers I and J. Node I is node J's parent in the tree of roads. 

A single line containing the integer that is the minimum number of roads that need to be destroyed for a subtree of P nodes to be isolated. 

[A subtree with nodes (1, 2, 3, 6, 7, 8) will become isolated if roads 1-4 and 1-5 are destroyed.] 

USACO 2002 February

#include <iostream>#include<stdio.h>#include<string.h>using namespace std;const int maxn=250;const int INF=0x3f3f3f3f;struct node{    int v;    node *next;} edge[maxn<<1],*head[maxn];int n,m,cnt,dp[maxn][maxn];void adde(int u,int v){    edge[cnt].v=v;    edge[cnt].next=head[u];    head[u]=&edge[cnt++];}void dfs(int fa,int u){    int i,j,v,mm=INF;    node *p;    dp[u][1]=0;    for(p=head[u];p!=NULL;p=p->next)    {        v=p->v;        if(v==fa)            continue;        dfs(u,v);        for(i=m;i>=1;i--)//01背包。從大到小裝        {            mm=dp[u][i]+1;//不要該子樹.            for(j=1;j<i;j++)//要該子樹                mm=min(mm,dp[u][j]+dp[v][i-j]);            dp[u][i]=mm;        }    }}int main(){    int i,u,v,ans;    while(~scanf("%d%d",&n,&m))    {        cnt=0;        memset(head,0,sizeof head);        memset(dp,0x3f,sizeof dp);        for(i=1;i<n;i++)        {            scanf("%d%d",&u,&v);            adde(u,v);            adde(v,u);        }        dfs(1,1);        ans=dp[1][m];        for(i=1;i<=n;i++)            ans=min(ans,dp[i][m]+1);//加1是因為根轉移了        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.