01背包之变形

链接:https://www.nowcoder.com/acm/contest/119/F
来源:牛客网

Beautiful Land
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
Now HUST got a big land whose capacity is C to plant trees. We have n trees which could be plant in it. Each of the trees makes HUST beautiful which determined by the value of the tree. Also each of the trees have an area cost, it means we need to cost ci area of land to plant.
We know the cost and the value of all the trees. Now HUSTers want to maximize the value of trees which are planted in the land. Can you help them?

输入描述:

There are multiple cases.
The first line is an integer T(T≤10), which is the number of test cases.
For each test case, the first line is two number n(1≤n≤100) and C(1≤C≤10
8
), the number of seeds and the capacity of the land. 
Then next n lines, each line contains two integer c
i
(1≤c
i
≤10
6
) and v
i
(1≤v
i
≤100), the space cost and the value of the i-th tree.

输出描述:

For each case, output one integer which means the max value of the trees that can be plant in the land.
示例1

输入

1
3 10
5 10
5 10
4 12

输出

22
#include<cstdio>价值背包
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<map>
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
typedef long long ll;
using namespace std;
#define N 10005
ll dp[N],w[N];  ///此时的dp[i]表示的是;价值为i时的最小容量为dp[i];
int v[N];
 
int main()
{
    int T,i,n,sum;
    ll V;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%I64d",&n,&V);
        sum=0;
        for(i=1;i<=n;i++)
        {
            scanf("%I64d%d",&w[i],&v[i]);
            sum=sum+v[i];
        }
 
        memset(dp,1000000010,sizeof(dp)); ///要求最小容量,初始化为最大值;
        dp[0]=0;
        for(i=1;i<=n;i++)
        {
            for(int j=sum;j>=v[i];j--)
                dp[j]=min(dp[j],dp[j-v[i]]+w[i]);
        }
 
        for(i=sum;i>=0;i--)
        {
            if(dp[i]<=V)
            {
               printf("%d
",i); ///此处输出i,即为满足条件的最大价值
               break;
            }
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/passion-sky/p/8998720.html