60分 求助!
查看原帖
60分 求助!
1840033
Wangxuhan_02楼主2025/8/31 16:15
#include <bits/stdc++.h>
using namespace std;

inline int fast_read() {
    static char buf[1 << 24];
    static int ptr = 0;
    static int len = 0;

    while (ptr >= len) {
        len = fread(buf, 1, sizeof(buf), stdin);
        ptr = 0;
        if (len == 0) return 0;
    }

    while (ptr < len && buf[ptr] <= ' ') {
        ptr++;
        if (ptr >= len) {
            len = fread(buf, 1, sizeof(buf), stdin);
            ptr = 0;
            if (len == 0) return 0;
        }
    }

    int x = 0;
    while (ptr < len && buf[ptr] >= '0' && buf[ptr] <= '9') {
        x = x * 10 + (buf[ptr] - '0');
        ptr++;
        if (ptr >= len) {
            len = fread(buf, 1, sizeof(buf), stdin);
            ptr = 0;
            if (len == 0) break;
        }
    }
    return x;
}

int main() {
    int n = fast_read();
    
    if (n == 1) {
        fast_read();
        puts("0");
        return 0;
    }

    int* a = new int[n];
    for (int i = 0; i < n; ++i) {
        a[i] = fast_read();
    }
    sort(a, a + n);

    long long* B = new long long[n - 1];
    int cnt_b = 0;
    int i = 0, j = 0;
    long long total = 0;
    long long x, y;

    for (int step = 0; step < n - 1; ++step) {
        if (i < n) {
            if (j >= cnt_b) {
                x = a[i++];
            } else {
                x = (a[i] <= B[j]) ? a[i++] : B[j++];
            }
        } else {
            x = B[j++];
        }

        if (i < n) {
            if (j >= cnt_b) {
                y = a[i++];
            } else {
                y = (a[i] <= B[j]) ? a[i++] : B[j++];
            }
        } else {
            y = B[j++];
        }

        long long sum = x + y;
        total += sum;
        B[cnt_b++] = sum;
    }

    printf("%lld\n", total);

    delete[] a;
    delete[] B;
    return 0;
}
2025/8/31 16:15
加载中...