题解:P17010 [GESP202606 五级] 排排坐

· · 题解

P17010 [GESP202606 五级] 排排坐 题解

个人认为今年五级不难,这题也挺水了吧

题目传送门

思路

这道题是让我们求小朋友们分到的糖果总量的最大值,不难

想到若要最大,应使前面的数字大。

结论证明

设 x_i,表示第 i 个小朋友手心写的数字,那么

总糖果数 = x_1 + (x_1+x_2) + (x_1+x_2+x_3) + \dots + (x_1+\dots+x_n)

即

n\cdot x_1 + (n-1)\cdot x_2 + (n-2)\cdot x_3 + \dots + 1\cdot x_n

故最优策略为:大数放左边,小数放右边(数组降序排列)。

结论有了,那就直接上代码。 ::::success[AC code]


#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2001;
int a[MAXN];
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    sort(a, a + n, greater<long long>()); // 最后逆序也可以用reverse,个人习惯用greater
    long long sum_candy = 0;
    for (int i = 0; i < n; ++i) {
        long long temp = (long long) a[i] * (n - i);
        sum_candy += temp;
    }
    cout << sum_candy;
    return 0;
}
::::
时间复杂度 $O(n \log n)$,足以通过此题。 

[AC = 4ms记录](https://www.luogu.com.cn/record/283392173)