题目:有n字符的种类,每种字符都有一个值和金额。她想使用其中一些字符构造一个字符串。定义字符串的值为:其第一个字符的值*1+其第二个字符的值*2+...计算可以构造的字符串的最大值。
思路:价值越高的越往后放,考虑到有负数价值的存在,所以我通过for循环找到找出字符中绝对值大于最大字符价值的最大负价值字符。然后将这个字符视为第一个,再用一个for循环一直加到最大价值字符。
代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 1000;
// 定义字符属性,包含价值和数量
struct Attribute {
int value; // 价值
int number; // 数量
}Character[N];
// 按照字符价值从大到小排序
bool compare(const Attribute& a, const Attribute& b) {
return a.value > b.value;
}
int main() {
int n;
cout << "请输入字符的数量:";
cin >> n;
int max = 0; // 初始化最大价值为0
for (int i = 0; i < n; i++) {
cout << "请输入这个字符的价值和数量:";
cin >> Character[i].value >> Character[i].number; // 输入每个字符的属性
}
sort(Character, Character + n, compare); // 对作业进行排序
// 找出字符中绝对值大于最大字符价值的最大负价值字符
int i = 1;
for (; i < n; ) {
if (Character[0].value + Character[i].value <= 0) {
break;
}
else
{
i++;
}
}
int m = 1;
for (; i > 0; ) {
max += Character[i-1].value * m;
m++;
Character[i-1].number--;
if (Character[i-1].number == 0) {
i--;
}
}
cout << "字符串的最大价值为:" << max << endl;
return 0;
}
输入例子:
请输入字符的数量:4
请输入这个字符的价值和数量:5 2
请输入这个字符的价值和数量:4 1
请输入这个字符的价值和数量:3 1
请输入这个字符的价值和数量:-5 1
输出例子:
字符串的最大价值为:46
代码中自己感觉还存在挺多不足的地方,希望大佬们能指点指点我!!