ZOJ-3211(砍树问题)-(01背包)

Dream City

Time Limit: 1 Second      Memory Limit: 32768 KB

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 nmai 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

Hints:
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.

题意:有n颗树,每棵树都有固定的初始值a[i],和有增长值b[i],给出m天,每天只能砍一棵树,那么对与第j天,如果选择砍掉第i棵树,那么收获的硬币就是a[i]+b[i]*(j-1),怎样砍才能使收获的硬币最多

解题思路:增长快的要放在后面砍会比较有利。在做背包前,要先排个序,可将问题转化为01背包问题。dp[i][j]表示前i课树,第j天所能取到的最大值。状态转移方程 : dp[i][j] = max(dp[i-1][j], dp[i-1][j-1] + x[i].a + (j-1)*x[i].b)


博客主要来自:

https://blog.csdn.net/a664607530/article/details/70148259

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef struct node
{
    int a,b;
}node;
node x[300];
int dp[300][300];
int cmp(node p,node q){
    if(p.b==q.b) return p.a<q.a;
    else return p.b<q.b;
}
int main()
{
    int t;  scanf("%d",&t);
    while(t--){
        int n,m;
        scanf("%d %d",&n,&m);
        for(int i=1;i<=n;i++) scanf("%d",&x[i].a);
        for(int i=1;i<=n;i++) scanf("%d",&x[i].b);
        sort(x+1,x+1+n,cmp);
        memset(dp,0,sizeof dp);;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]+x[i].a+x[i].b*(j-1));
        printf("%d\n",dp[n][m]);
    }
    return 0;
}


阅读更多
个人分类: 题库
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

ZOJ-3211(砍树问题)-(01背包)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭