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

using namespace std;

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

    vector<pair<int, int>> Ap(n);

    long long sum = 0;
    for (int i = 0; i < n; ++i) {
        Ap[i] = {A[i], i};
        sum += A[i];
    }

    sort(Ap.begin(), Ap.end());

    vector<long long> pref(n + 1);
    for (int i = 0; i < n; ++i) {
        pref[i + 1] = pref[i] + Ap[i].first;
    }

    int ptr = n;
    long long suff = 0;
    vector<int> qans(n + 1), qptr(n + 1);

    int mn = n + 1, mni = -1;
    for (int i = n - 1; i >= 0; --i) {
        suff += Ap[i].first;
        while (ptr >= 0 && suff >= (sum + 1) / 2 - pref[ptr]) {
            qans[ptr] = abs(n - 2 * max(ptr, i) + 2 * ptr);
            qptr[ptr] = max(ptr, i);

            if (mn > qans[ptr]) {
                mn = qans[ptr], mni = ptr - 1;
            }

            --ptr;
        }
    }

    ptr = 0;
    vector<int> ans(n);
    for (int i = 0; i <= mni; ++i) {
        ans[ptr++] = (Ap[i].second);
    }

    int l = qptr[mni + 1];
    for (int i = l; i < n; ++i) {
        ans[ptr++] = (Ap[i].second);
    }

    for (int i = mni + 1; i < l; ++i) {
        ans[ptr++] = (Ap[i].second);
    }

    return ans;
}
