01 Backpack deformation

It is widely believed that there are countless trees on the Huazhong campus.

Now HUST gets a large piece of land with capacity C to plant trees. We have n trees that can be planted in it. Every tree makes HUST beautiful, which is determined by the value of the tree. Also each tree has an area cost, which means we need the cost of C I land, plant area.
We know the cost and value of all trees. Now, HUSTers want to maximize the value of the trees planted on the land. Can you help them?

Enter description:

There are multiple situations. 
The first line is an integer T (T ≤ 10), which is the number of test cases.
For each test case, the first line is the two numbers n (1≤n≤100) and C (1≤C≤10 ), the number of seeds and the capacity of the land. Then the next n lines, each containing two integers C

I

(1≤C

I

≤10

6

) and v

I

(1≤v

I

≤ 100), the value of the ith tree of space and cost.

Output description:

For each case, output an integer, which means the maximum number of trees that can be planted on the land.

Example 1

enter

1
3 10
5 10
5 10
4 12

output

22 To the 


effect
of the question, the meaning of the title is a 01 backpack problem, but its data is the eighth power of 10, so the template cannot be directly applied. This question needs to be transformed accordingly.
Originally, the 01 backpack needs to create a two-dimensional array, and then dp the weight , calculate the maximum value that can be achieved at the current weight, but it will burst the memory,
so I changed my mind, I dp the minimum weight that can be obtained for each value, and then judge whether it is less than the limit weight given by the input;
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
const int MAX = 1e2 + 5;
const int MAXSIZE = 0x3f3f3f3f;
using namespace std;
 
int t, n, C, v[MAX], c[MAX];
int main(){
    int dp[10005];
    int maxV;
    scanf("%d", &t);
    while (t--)
    {
        memset(dp, MAXSIZE, sizeof(dp));
        maxV = 0;
        scanf("%d %d", &n, &C);
        for (int i = 0; i < n; i++)
        {
            scanf("%d %d", &c[i], &v[i]);
            maxV + = v [i];
        }
        dp[0] = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = maxV; j >= v[i]; j--)
            {
                dp[j] = min(dp[j], dp[j - v[i]] + c[i]);
            }
        }
        for (int i = maxV; i >= 0; i--){
            if (dp[i] <= C){
                printf("%d\n", i);
                break;
            }
        }
    }
    return 0;
}

 

There is also a rolling array (which can save a lot of memory). Next time, I will 
borrow two Daniel blogs
https://www.cnblogs.com/GNLin0820/p/6434693.html
https://blog.csdn. net/u012965373/article/details/52180788
Through this question, I became proficient with the 01 backpack and deepened the dp idea
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325377917&siteId=291194637