ALGO-30 Algorithm Training Entrance Exam

Resource limit
Time limit: 1.0s Memory limit: 256.0MB

Problem description
  Chenchen is a talented child, and his dream is to become the greatest doctor in the world. For this reason, he wanted to learn from the most prestigious doctor 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 herbs in this cave. It takes some time to pick each plant, and each plant has its own value. I will give it to you." You have a period of time. During this time, you can collect some herbs. If you are a smart child, you should be able to maximize the total value of the herbs you collect.” If you are Chenchen, you can complete this
  task ?
  
The first line of the input format
  has two integers T (1 <= T <= 1000) and M (1 <= M <= 100), separated by a space, T represents the total time that can be used to collect herbs, and M represents The number of herbs in the cave. Each of the next M lines contains two integers between 1 and 100 (including 1 and 100), which respectively represent the time when a certain herb was picked and the value of this herb.
The output format
  includes one line, which only contains an integer, indicating the maximum total value of herbs that can be collected within the specified time.
  
Sample input
70 3
71 100
69 1
1 2

Sample output
3

Data size and conventions
  For 30% of the data, M <= 10;
  for all the data, M <= 100.
  
Question URL
http://lx.lanqiao.cn/problem.page?gpid=T92


It is the principle of 01 backpack, directly use dynamic programming

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

int main()
{
    
    
    int t;//总共能够用来采药的时间
    int m;//山洞里的草药的数目
    scanf("%d %d",&t,&m);
    int dp[m+1][t+1];
    memset(dp,0,(t+1)*(m+1));//初始化
    int w[m+1];//采摘某株草药的时间
    int v[m+1];//这株草药的价值
    int i,j;

    for(i=1;i<=m;i++)
    {
    
    
        scanf("%d %d",&w[i],&v[i]);
    }
    //可能遇到数组下标为负的情况,从1开始
    for(i=1;i<m+1;i++)//1~m个草药
    {
    
    
        for(j=1;j<t+1;j++)//1~t的时间
        {
    
    
            if(j<w[i]){
    
    //假如时间不满足,不足以采摘
                dp[i][j]=dp[i-1][j];//不拿此草药,保持上一个草药集合的价值
            }
            else{
    
    
            //如果时间足够,上一件采摘药草集合的值,和舍弃w[i]时间期间的草药,再摘当前草药的值进行对比
            //如果上一个草药集合的值大,就不摘当前草药,保持上一个草药的值
            //如果摘当前草药比较大,就选择摘当前草药,舍弃相应先前w[i]草药时间的值
                dp[i][j]=dp[i-1][j]>dp[i-1][j-w[i]]+v[i]?dp[i-1][j]:dp[i-1][j-w[i]]+v[i];
            }
        }
    }
    printf("%d",dp[m][t]);//最后一个格子是相应结果
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_49868778/article/details/115280657