题目描述
北大网络实验室经常有活动需要叫外卖,但是每次叫外卖的报销经费的总额最大为C元,有N种菜可以点,经过长时间的点菜,网络实验室对于每种菜i都有一个量化的评价分数(表示这个菜可口程度),为Vi,每种菜的价格为Pi, 问如何选择各种菜,使得在报销额度范围内能使点到的菜的总评价分数最大。 注意:由于需要营养多样化,每种菜只能点一次。
输入描述:
输入的第一行有两个整数C(1 <= C <= 1000)和N(1 <= N <= 100),C代表总共能够报销的额度,N>代表能点菜的数目。接下来的N行每行包括两个在1到100之间(包括1和100)的的整数,分别表示菜的>价格和菜的评价分数。
输出描述:
输出只包括一行,这一行只包含一个整数,表示在报销额度范围内,所点的菜得到的最大评价分数。
示例1
输入
90 4
20 25
30 20
40 50
10 18
40 2
25 30
10 8
输出
95
38
题目解析:0,1背包问题,物品只能使用一次(看0,1背包问题,看我的0,1背包)
例如:解过程实际上就是求最大值的过程,只有w1,v1时,weight<=1,没有符合重量的物品,所以为0,所以新进入一个物品,更新在某重量下的最大值。
代码:
#include <stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<vector>
#include<map>
#include<iomanip>
const int N = 100;
using namespace std;
typedef struct{
int price;
int score;
}Food;
int main() {
int dp[1001];
Food food[N];
int total,count; //额度,数目
while(cin >> total >> count){
for(int i = 0 ; i< count; i++){
cin >> food[i].price >> food[i].score;
}
memset(dp,0,sizeof(dp));
for(int i = 0 ; i < count; i++){
for(int j = total;j >= food[i].price;j--){
dp[j] = dp[j] > dp[j - food[i].price] + food[i].score ? dp[j] : dp[j - food[i].price] +food[i].score; //更新数组
}
}
cout << dp[total] << endl;
}
return 0;
}