关闭

练习3-Q

85人阅读 评论(0) 收藏 举报

题目:Problem Q

Problem Description
Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …<br>The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?<br><center><img src=../../../data/images/C154-1003-1.jpg> </center><br>

Input
The first line contain a integer T , the number of cases.<br>Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output
One integer per line representing the maximum of the total value (this number will be less than 2<sup>31</sup>).

Sample Input
1 5 10 1 2 3 4 5 5 4 3 2 1

Sample Output
14

题意:

01背包问题,往体积为V的背包里放体积和价值不同的东西,求背包被放满时的最大价值;

思路:

只考虑第i件物品放或不放,如果第i件物品可以放得开,则其动态转移方程为
dp[i][j] = max(dp[i-1][j], dp[i-1][j-vo[i]]+va[i]);
其中i表示第i件物品,j表示放入第i件物品后的体积。

代码:

# include <iostream>
# include <string.h>
# include <algorithm>

using namespace std;

int dp[1001][1001];



int main()
{
    int va[1001], vo[1001];
    int T;
    cin >> T;
    while(T--)
    {
        memset(va,0,sizeof(va));
        memset(vo,0,sizeof(vo));
        memset(dp,0,sizeof(dp));
        int N, V;
        cin >> N >> V;
        for(int i = 1;i <= N; i++)
            cin >> va[i];
        for(int i = 1;i <= N; i++)
            cin >> vo[i];


        for(int i = 1;i <= N; i++)
        {
            for(int j = 0;j <= V; j++)
            {
                if(vo[i] <= j)
                    dp[i][j] = max(dp[i-1][j], dp[i-1][j-vo[i]]+va[i]);
                else
                    dp[i][j] =dp[i-1][j];
            }
        }

        /*for(int i = 1;i <= N; i++)
        {
            for(int j = 0;j <= V; j++)
                cout << dp[i][j] << " ";
            cout << endl;
        }*/
            cout << dp[N][V]<<endl;
    }

    return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2712次
    • 积分:282
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条