题解 020:P12218 [蓝桥杯 2023 国 Java B] 玩具

· · 题解

思路

题目说,要将 2 \times n 个数字配对成 n 对,每对的权重为两个数字的乘积,求所有权重的和的最小值。
如果要让权重的和最小,那么最佳的方案是让一个较小的数拉着一个较大的数,使乘积尽可能小。
于是我们可以把 w 数组排序,然后用两个指针 i 和 j 分别指向 1 和 2 \times n 的位置,然后向中间收拢,每次得到的乘积累加至 ans 中,最后输出 ans 即可。

代码

#include <bits/stdc++.h>
using namespace std;
#define int long long
//↑不开ll见祖宗
int ans, n, w[1000005];

signed main() {
    cin >> n;
    n *= 2;//处理二倍n
    for (int i = 1; i <= n; i++)
        cin >> w[i];
    sort(w + 1, w + n + 1);//排序
    for (int i = 1, j = n; i <= j; i++, j--)//双指针计算并输出
        ans += w[i] * w[j];
    cout << ans;
    return 0;
}

AC 记录