poj1947之删除最少边保留m个节点

Rebuilding Roads
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 8409 Accepted: 3763

Description

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.

Input

* 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. 

Output

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. 

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
题意:给定n个点,n-1条边,求删除最少的边使剩余子树有给定的p个节点数

分析:树形dp:以点u为根的树保留j个节点所需要删除的最少边,本题是无根树,在这里当做有根树(根为1)来处理,在dp过程中特别的比较下以u为根的树保留m个节点所需要删除的最少边即可,这样也达到了以任意点为根保留m个节点求最少删除的边。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include <map>
#include <cmath>
#include <iomanip>
#define INF 99999999
typedef long long LL;
using namespace std;

const int MAX=150+10;
int n,m,sum,size,head[MAX];
int dp[MAX],temp[MAX];

struct Edge{
	int v,next;
	Edge(){}
	Edge(int V,int NEXT):v(V),next(NEXT){}
}edge[MAX];

void Init(int num){
	for(int i=1;i<=num;++i)head[i]=-1;
	size=0;
}

void InsertEdge(int u,int v){
	edge[size]=Edge(v,head[u]);
	head[u]=size++;
}

int dfs(int u,int Id){
	int last=0,now=0;
	dp[Id]=0;
	for(int i=head[u];i != -1;i=edge[i].next){
		int v=edge[i].v;
		now=dfs(v,Id+last+1)+1;
		for(int j=last+1;j<=last+now;++j)dp[Id+j]=INF;
		for(int j=last;j>=0;--j){
			for(int k=1;k<=now;++k){
				dp[Id+j+k]=min(dp[Id+j+k],dp[Id+j]+temp[k-1]);
			}
			dp[Id+j]=dp[Id+j]+1;//k=0表示以点v为根的子树全部删除,只要删除u->v的枝干就行 
		}
		last+=now;
	}
	for(int i=0;i<=last;++i)temp[i]=dp[Id+i];
	if(last+1>=m)sum=min(sum,dp[Id+m-1]+1);//以点u作为根保留m个点需要删除的最少边 
	return last;
}

int main(){
	int u,v;
	while(~scanf("%d%d",&n,&m)){
		Init(n);
		for(int i=1;i<n;++i){
			scanf("%d%d",&u,&v);
			InsertEdge(u,v);
		}
		sum=INF;
		dfs(1,0);
		printf("%d\n",min(sum,dp[m-1]));
	}
	return 0;
}
/*
input:
12 7
1 11
1 12
1 2
2 3
2 4
4 5
4 8
5 6
5 7
8 9
8 10
output:
1
*/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值