题目描述
服装店新进了a条领带,b条裤子,c个帽子,d件衬衫,现在要把这些搭配起来售卖。有三种搭配方式,一条领带和一件衬衫,一条裤子和一件村衫,一个帽子和一件衬衫。卖出一套领带加村衫可以得到e元,卖出一套裤子加衬衫可以得到元,卖出一套帽子加衬衫可以得到g元。现在你需要输出最大的获利方式。
样例输入
2 3 4 5 6 7 8
样例输出
39
提示
4个帽子加4件衬衫获利32元,1条裤子加1件衬衫获利7元,一共得到39元。
开始拿到题目的时候看到有数的组合,本来想用vector<map<int,int>,int>来解决问题的,后来发现不能用迭代器类型获取到map中的数据,然后建立了一个与map结构相似的结构体替代相应的功能。代码如下
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include<map>
using namespace std;
class Solution {
public:
int mins(int x, int y) { return (x < y) ? x : y; }
void combine() {
cin >> a >> b >> c >> d >> e >> f >> g;
rest.emplace_back(make_pair(mp(a, d), e));
rest.emplace_back(make_pair(mp(b, d), f));
rest.emplace_back(make_pair(mp(c, d), g));
}
int calMaxValue() {
//降序排序,先找价值最大的
sort(rest.begin(), rest.end(), [=](pair<struct mp,int> &t1, pair<struct mp, int> &t2) {return t1.second > t2.second; });
for (int i=0; d > 0;i++) {
int num = mins(rest[i].first.x, rest[i].first.y);
maxValue += (rest[i].second)*(d>num?num:d);
d = (d > num) ? (d - rest[i].first.x) : 0;
}
return maxValue;
}
private:
int a, b, c, d, e, f, g;
//结构体
struct mp {
int x;
int y;
//有参构造方式
mp(int x, int y) :x(x), y(y) {};
};
vector<pair<struct mp,int>> rest;
int maxValue = 0;
};
int main() {
Solution s1;
s1.combine();
int MAX = s1.calMaxValue();
cout << "maxValue= " << MAX << endl;
return 0;
}
如果有什么问题,请与我联系,指出问题所在,我一定抓紧纠正,谢谢大家。