AcWing 913. 排队打水

题目传送门

一、分析题意

看样例:
2.png

$sum=3 * 6+6 * 5+1 * 4+4 * 3+2 * 2+5 * 1 $

二、算法思路

让最磨叽的人,最后打水,谁快就谁先来,节约大家时间。

推公式:
\(sum=\sum\limits_{i=1}^{n}(n-i+1)*a[i]\)

三、完整代码

#include <bits/stdc++.h>

using namespace std;
const int N = 100010;

typedef long long LL;
int a[N];
LL res;

int main() {
    //优化输入
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) cin >> a[i];
    sort(a, a + n);
    for (int i = 0; i < n; i++) res += a[i] * (n - i - 1);
    printf("%lld", res);
    return 0;
}
原文地址:https://www.cnblogs.com/littlehb/p/15459455.html