背包问题
时间限制:3000 ms | 内存限制:65535 KB
难度:3
- 描述
- 现在有很多物品(它们是可以分割的),我们知道它们每个物品的单位重量的价值v和重量w(1<=v,w<=10);如果给你一个背包它能容纳的重量为m(10<=m<=20),你所要做的就是把物品装到背包里,使背包里的物品的价值总和最大。
- 输入
- 第一行输入一个正整数n(1<=n<=5),表示有n组测试数据;
随后有n测试数据,每组测试数据的第一行有两个正整数s,m(1<=s<=10);s表示有s个物品。接下来的s行每行有两个正整数v,w。
- 输出
- 输出每组测试数据中背包内的物品的价值和,每次输出占一行。
- 样例输入
-
1
3 15
5 10
2 8
3 9
- 样例输出
-
65
背包问题,注意题目物品时可以分割的,按价值从大到小排个序,贪心求解
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
typedef pair<int,int> Good;
bool cmp(const Good& a,const Good& b){
return a.first > b.first;
}
int main(){
int n;
cin >>n;
for(int icase = 0 ; icase <n ; ++icase){
int s,m;
cin >>s >>m;
vector<Good> goods(s);
for(int i = 0 ; i < s; ++ i)
cin >> goods[i].first>>goods[i].second;
sort(goods.begin(),goods.end(),cmp);
int res = 0;
for(int i = 0 ; i < s && m> 0; ++ i){
if(m > goods[i].second){
m-=goods[i].second;
res+=goods[i].first*goods[i].second;
}else{
res+=goods[i].first*m;
break;
}
}
cout<<res<<endl;
}
}