#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
#include "partition.h"

using namespace std;

const int N = 2e6 + 5;

vector<int> solve(vector<int> A) {
    int n = A.size();

    long long sum = 0;
    vector<int> Ap(n + 1);
    for (int i = 0; i < n; ++i) {
        Ap[i + 1] = i;
        sum += A[i];
    }
    sum = (sum + 1) / 2;

    sort(Ap.begin() + 1, Ap.end(), [&](int a, int b){
        return A[a] < A[b];
    });

    int ptr = n + 1;
    long long pref = 0, suff = 0;

    int mn = n + 1, mni = -1, mnj = -1;
    while (ptr >= 1) {
        suff += A[Ap[--ptr]];
        if (suff >= sum) {
            break;
        }
    }

    int cur = 0, to = (n + 1) / 2;
    for (int i = 0; i <= to; ++i) {
        while (ptr <= n && (i >= ptr || pref + suff - A[Ap[ptr]] >= sum)) {
            suff -= A[Ap[ptr++]];
        }

        cur = n + 2 * i + 2 - 2 * ptr;

        if (mn > cur) {
            mn = cur, mni = i, mnj = ptr;
        }

        pref += A[Ap[i + 1]];
    }

    ptr = 0;
    for (int i = 1; i <= mni; ++i) {
        A[ptr++] = (Ap[i]);
    }

    for (int i = mnj; i <= n; ++i) {
        A[ptr++] = (Ap[i]);
    }

    for (int i = mni + 1; i < mnj; ++i) {
        A[ptr++] = (Ap[i]);
    }

    return A;
}
