ACM: 动态规划题 poj 1947

来源:互联网 发布:金山tw域名遭抢注 编辑:程序博客网 时间:2024/06/16 09:10
RebuildingRoads
Description
The cows have reconstructedFarmer John's farm, with its N barns (1 <= N<= 150, number 1..N) after the terrible earthquakelast May. The cows didn't have time to rebuild any extra roads, sonow there is exactly one way to get from any given barn to anyother barn. Thus, the farm transportation system can be representedas a tree.

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

Input

* Line 1: Two integers, N andP

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

Output

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

Sample Input

11 6
1 2
1 3
1 4
1 5
2 6
2 7
2 8
4 9
4 10
4 11

Sample Output

2

 

题意: 在一棵树结构上, 要求断开最少的边可以得到节点个数为P的子树.

 

解题思路:

     1. 题目很简单, 可以使用线性dp的思路, 设状态dp[i][j]: 以i为根,保留j个节点的最小消耗.

         易得动态方程:dp[i][j+k] = min(dp[i][j]+dp[ g[i][v] ][k]-2);

               (g[i][v]:表示i的相邻节点v,因为2棵子树要合并, 相邻边多删除了2次)

     2. 初始化: 当i == root时: dp[i][1] = 相邻节点个数. (一个节点一条边)

                         否则: dp[i][1] = 相邻节点个数 + 一个父亲节点个数.

     3. 递推的方向自下而上即可.

 

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 155
const int INF = (1<<29);

int n, p, root;
int g[MAX][MAX], num[MAX], flag[MAX];
int dp[MAX][MAX];

inline int min(int a, int b)
{
 return a < b ? a : b;
}

void dfs(int u)
{
 int i, j, k;
 for(i = 0; i < num[u]; ++i)
  dfs(g[u][i]);
 if(u == root) dp[u][1] = num[u];
 else dp[u][1] = num[u]+1;

 for(i = 0; i < num[u];++i)
 {
  for(j = p-1; j>= 1; --j)
  {
   if(dp[u][j]< INF)
   {
    for(k= 1; j+k <= p; ++k)
    {
     if(dp[g[u][i] ][k] < INF)
      dp[u][j+k]= min(dp[u][j+k], dp[u][j]+dp[ g[u][i] ][k]-2);
    }
   }
  }
 }
}

int main()
{
// freopen("input.txt", "r", stdin);
 int u, v, i, j;
 while(scanf("%d %d",&n,&p) != EOF)
 {
  memset(num, 0,sizeof(num));
  memset(flag, 0,sizeof(flag));
  memset(g, 0, sizeof(g));
  for(i = 0; i <=n; ++i)
   for(j = 0; j<= n; ++j)
    dp[i][j]= INF;

  for(i = 1; i< n; ++i)
  {
   scanf("%d%d",&u, &v);
   g[u][num[u]++ ] = v;
   flag[v] =1;
  }

  for(i = 1; i<= n; ++i)
  {
   if(flag[i] ==0)
   {
    root= i;
    break;
   }
  }
  dfs(root);
  
  int result = INF;
  for(i = 1; i <=n; ++i)
   result =min(result, dp[i][p]);
  printf("%d\n", result);
 }
 return 0;
}

0 0
原创粉丝点击