complete knapsack problem

Topic description

LiYuxiang is a gifted and intelligent child whose dream is to become the greatest physician in the world. To this end, he wanted to learn from the most prestigious physicians nearby. In order to judge his qualifications, the doctor gave him a difficult problem. The doctor took him to a cave full of herbs and said to him: "Son, there are some different kinds of herbs in this cave. It takes some time to pick each one, and each one has its own value. I will Give you a period of time during which you can pick up some herbs. If you're a smart kid, you should be able to maximize the total value of the herbs you pick."

If you are LiYuxiang, can you complete this task?

Differences between this question and the original question:

1. Each herb can be wildly picked without limit.

2. The types of medicines are dazzling, and it takes a long time to collect medicines! Thank you for waiting for the chrysanthemum!

Idea: Complete knapsack problem, there are two kinds of codes here

#include<iostream>
#include<cstdio>
#define X 100000+7
using namespace std;
int f[X],w[X],t[X];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d",t+i,w+i);
    }
    for(int i=1;i<=m;++i)
    {
        for(int j=0;j<=n;++j)
        {
            if(t[i]<=j)
            f[j]=max(f[j],f[j-t[i]]+w[i]);
        }
    }
    cout<<f[n];
}

Solution 2: Note: not all A's

#include<iostream>
#include<cstdio>
#define X 10000+7
using namespace std;
int v[X],w[X],f[1000][1000];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d",v+i,w+i);
    }
    for(int i=1;i<=m;++i)
    {
        for(int j=1;j<=n;++j)
        {
            if(j>=v[i])
            for(int k=0;k<=j/v[i];++k)
            f[i][j]=max(f[i][j],f[i-1][j-k*v[i]]+k*w[i]);
            else
            f[i][j]=f[i-1][j];
        }
    }
    cout<<f[m][n];
}

 

Guess you like

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