[AcWing] 913. 排队打水(C++实现)贪心---排序不等式例题
1. 题目
2. 读题(需要重点注意的东西)
思路:
贪心 -----> 每次在当前的选法中,选择能选的情况中的最优解
解题思路:
代码实现思路:
按上述思路,只需要代入公式即可:res += t[i] * (n-i-1);
3. 解法
---------------------------------------------------解法---------------------------------------------------
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
int n;
int t[N];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i ++ ) scanf("%d", &t[i]);
// 按从小到大排序
sort(t, t + n);
LL res = 0;
for (int i = 0; i < n; i ++ ) res += t[i] * (n-i-1);
printf("%lld\n", res);
return 0;
}
可能存在的问题(所有问题的位置都在上述代码中标注了出来)
4. 可能有帮助的前置习题
5. 所用到的数据结构与算法思想
- 贪心
6. 总结
贪心思想、排序不等式的例题,理解思想并自行推导出公式。