The more, The Better
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4298 Accepted Submission(s): 2542
Problem Description
ACboy很喜欢玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中ACboy允许攻克M个城堡并获得里面的宝物。但由于地理位置原因,有些城堡不能直接攻克,要攻克这些城堡必须先攻克其他某一个特定的城堡。你能帮ACboy算出要获得尽量多的宝物应该攻克哪M个城堡吗?
Input
每个测试实例首先包括2个整数,N,M.(1 <= M <= N <= 200);在接下来的N行里,每行包括2个整数,a,b. 在第 i 行,a 代表要攻克第 i 个城堡必须先攻克第 a 个城堡,如果 a = 0 则代表可以直接攻克第 i 个城堡。b 代表第 i 个城堡的宝物数量, b >= 0。当N = 0, M = 0输入结束。
Output
对于每个测试实例,输出一个整数,代表ACboy攻克M个城堡所获得的最多宝物的数量。
Sample Input
3 2 0 1 0 2 0 3 7 4 2 2 0 1 0 4 2 1 7 1 7 6 2 2 0 0
Sample Output
5 13
Author
8600
Source
Recommend
LL
树形DP , 泛化背包
dp[i][j]表示当节点为i时攻克j个点时获得的财富 , 最初看起来这题并不是一棵树,的确是一片森林,但是我们可以给他加一个虚拟的根节点,组成一棵树,然后再去DFS即可!
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <map>
#include <string>
#include <stack>
#include <cctype>
#include <vector>
#include <queue>
#include <set>
#include <utility>
using namespace std;
//#define Online_Judge
#define outstars cout << "***********************" << endl;
#define clr(a,b) memset(a,b,sizeof(a))
#define lson l , mid , rt << 1
#define rson mid + 1 , r , rt << 1 | 1
#define mk make_pair
#define FOR(i , x , n) for(int i = (x) ; i < (n) ; i++)
#define FORR(i , x , n) for(int i = (x) ; i <= (n) ; i++)
#define REP(i , x , n) for(int i = (x) ; i > (n) ; i--)
#define REPP(i ,x , n) for(int i = (x) ; i >= (n) ; i--)
const int MAXN = 200 + 50;
const long long LLMAX = 0x7fffffffffffffffLL;
const long long LLMIN = 0x8000000000000000LL;
const int INF = 0x7fffffff;
const int IMIN = 0x80000000;
#define eps 1e-8
#define mod 1000000007
typedef long long LL;
const double PI = acos(-1.0);
typedef double D;
typedef pair<int , int> pi;
///#pragma comment(linker, "/STACK:102400000,102400000")
int dp[MAXN][MAXN], value[MAXN] , head[MAXN];
int cnt =0;
int n , m ;
struct Node
{
int u , next;
}edge[MAXN];
void addedge(int u , int v)
{
edge[cnt].u = v;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void dfs(int cur)
{
int t = 0 , p = 0 , v = 0 , max_dp = 0;
dp[cur][0] = 0;
for(p =head[cur] ; p != -1 ; p = edge[p].next)
{
v = edge[p].u;
dfs(v);
REP(i , m , 0)
{
max_dp = dp[cur][i];
if(cur == 0)t = i;
else t = i - 1;
FORR(j , 0 , t)
{
max_dp = max(max_dp , dp[v][j] + dp[cur][i - j]);
}
dp[cur][i] = max_dp;
}
}
FORR(i ,1 , m)dp[cur][i] += value[cur];
}
int main()
{
//ios::sync_with_stdio(false);
#ifdef Online_Judge
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif // Online_Judge
int u , cost;
while(~scanf("%d%d" , &n , &m) , (n || m))
{
value[0] = 0;
clr(head , -1);
clr(edge , 0);
clr(dp , 0);
cnt = 0;
FOR(i , 0, n)
{
scanf("%d%d" , &u , &cost);
value[i + 1] = cost;
addedge(u , i + 1);
}
dfs(0);
printf("%d\n" ,dp[0][m]);
}
return 0;
}