题目描述
lcy0x1 去服务器的系统商店买东西。
一个人的背包有 21 格。
一开始他的背包里有 m 件不同的物品(不能卖)。
他要买 n 种物品,第 i 件物品的名字为 sti,有 ai 件,价值为 bi,一格可以放 ci 个。
相同的物品可以放同一格(只要没放满)。
问:他跑一次最多能卖多少钱。
输入格式
第一行两个整数 m,n。
下面 n 行,第 i+1 行三个整数 ai,bi,ci 与一个字符串 sti。
输出格式
最多卖的钱 s。
输入输出样例
输入
20 3 63 1 64 yinshifen 1 10 1 men 1 1 64 yinshifen
输出
64
代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct thing{
int a;
int b;
int c;
string name;
}th[1000];
bool cmp(thing a,thing b){
return a.b>b.b;
}
int n,m,ans,i,o;
int main() {
cin>>m>>n;
m=21-m;
for(i=1;i<=n;i++){
cin>>th[i].a>>th[i].b>>th[i].c>>th[i].name;
}
for(i=1;i<n;i++){
for(o=i+1;o<=n;o++){
if(th[i].name==th[o].name) {
if(th[i].a+th[o].a>th[i].c) {
th[o].a+=th[i].a;
th[o].a-=th[i].c;
th[i].a=th[i].c;
} else {
th[i].a+=th[o].a;
th[o].a=0;
}
}
}
}
for(i=1;i<=n;i++){
th[i].b*=th[i].a;
}
sort(th+1,th+n+1,cmp);
i=1;
while(m--) {
ans+=th[i++].b;
}
cout<<ans;
return 0;
}
里面有一些情况没有考虑到,但大体是这个样子的。
简单解释一下这个代码:最开始的两个for循环是为了找出有没有一样的物品有就合并一下,然后把合并多了的做一个处理;之后的for循环是算出每一个物品的价值,然后进行sort排序把最高价值的排在前面然后进行输出就可以了;