标签:err mem output its asc inpu mod tmp sam
Rebuilding Roads
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 10653 Accepted: 4884
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
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
Hint
[A subtree with nodes (1, 2, 3, 6, 7, 8) will become isolated if roads 1-4 and 1-5 are destroyed.]
Source
USACO 2002 February
题目链接:
http://poj.org/problem?id=1947
题意:
给你一棵节点为n的树。问至少砍几刀能够孤立出一棵节点为m的子树。
思路:
找到根节点(入度为0)后dfs在每一个节点统计dp[i][j]
表示i及其的子树保留j个节点的最小代价;
int tmp=dp[x][ii]+1;//不要y节点;
tmp=min(tmp,dp[x][ii-j]+dp[y][j]);
dp[x][ii]=tmp;
y为x的儿子节点。
代码:
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<vector>
using namespace std;
int dp[155][155];
int ans;
int in[155];
vector<int> lin[155];
int n,aa,bb,p;
void dfs(int x)
{
for(int i=2;i<=p;i++) dp[x][i]=99999999;
if(lin[x].size()==0)
dp[x][1]=0;
for(int i=0;i<lin[x].size();i++)
{
int y=lin[x][i];
dfs(y);
for(int ii=p;ii>=1;ii--)
{
int tmp=dp[x][ii]+1;
for(int j=1;j<ii;j++)
tmp=min(tmp,dp[x][ii-j]+dp[y][j]);
dp[x][ii]=tmp;
}
}
}
int main()
{
scanf("%d%d",&n,&p);
{
int ans=99999999;
for(int i=1;i<n;i++)
{
scanf("%d%d",&aa,&bb);
lin[aa].push_back(bb);
in[bb]++;
}
for(int i=1;i<=n;i++)
if(!in[i])
{
dfs(i);
ans=dp[i][p];
break;
}
for(int i=1;i<=n;i++)
ans=min(ans,dp[i][p]+1);
printf("%d\n",ans);
}
}
[poj 1947] Rebuilding Roads 树形DP
标签:err mem output its asc inpu mod tmp sam
原文地址:http://www.cnblogs.com/tlnshuju/p/7389077.html