Dream City
JAVAMAN is visiting Dream City and he sees a yard of gold coin trees. There are n trees in the yard. Let's call them tree 1, tree 2 ...and tree n. At the first day, each tree i has ai coins on it (i=1, 2, 3...n). Surprisingly, each tree i can grow bi new coins each day if it is not cut down. From the first day, JAVAMAN can choose to cut down one tree each day to get all the coins on it. Since he can stay in the Dream City for at most m days, he can cut down at most m trees in all and if he decides not to cut one day, he cannot cut any trees later. (In other words, he can only cut down trees for consecutive m or less days from the first day!)
Given n, m, ai and bi (i=1, 2, 3...n), calculate the maximum number of gold coins JAVAMAN can get.
Input
There are multiple test cases. The first line of input contains an integer T (T <= 200) indicates the number of test cases. Then T test cases follow.
Each test case contains 3 lines: The first line of each test case contains 2 positive integers n and m (0 < m <= n <= 250) separated by a space. The second line of each test case contains n positive integers separated by a space, indicating ai. (0 < ai <= 100, i=1, 2, 3...n) The third line of each test case also contains n positive integers separated by a space, indicating bi. (0 < bi <= 100, i=1, 2, 3...n)
Output
For each test case, output the result in a single line.
Sample Input
2 2 1 10 10 1 1 2 2 8 10 2 3
Sample Output
10 21
Hint s:
Test case 1: JAVAMAN just cut tree 1 to get 10 gold coins at the first day.
Test case 2: JAVAMAN cut tree 1 at the first day and tree 2 at the second day to get 8 + 10 + 3 = 21 gold coins in all.
这个题看上去就是一个01背包唯一不同的是每一个物品的价值是不断变化的,所以这是要根据他们的单位变化量进行排序,单位变化大的放在后面代表尽量靠后拿,也就是先需要贪心,再dp,以前没有见过类似的题,所以就没有排序就不过,算是又长见识了
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m,dp[500][500];
struct node{
int val,w;
}a[500];
bool cmp(node x,node y){
return x.w < y.w;
}
int main(){
int t,sum;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++){
scanf("%d",&a[i].val);
}
for(int i = 1; i <= n; i++){
scanf("%d",&a[i].w);
}
memset(dp,0,sizeof(dp));
sort(a+1,a+1+n,cmp);
for(int i = 1; i <= n; i++){
for(int j = m; j >= 1; j--){
dp[i][j] = max(dp[i-1][j],dp[i-1][j-1] + a[i].val + a[i].w * (j - 1));
}
}
printf("%d\n",dp[n][m]);
}
return 0;
}
本文介绍了一道经典的01背包变种问题——在DreamCity中寻找最优金币获取策略。JAVAMAN需要在有限天数内从n棵金币树中获取最多金币,每棵树的金币数量随时间增加。通过贪心策略结合动态规划求解最大收益。
542

被折叠的 条评论
为什么被折叠?



