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

using namespace std;

const int N = 2e6 + 5;

int Ap[N];

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

    bool sub4 = 1;
    long long sum = 0;
    for (int i = 0; i < n; ++i) {
        Ap[i + 1] = i;
        sum += A[i];

        sub4 = (A[i] - 1 != i ? 0 : sub4);
    }
    sum = (sum + 1) / 2;

    if (sub4) {
        vector<int> ans(n);
        int ptr = 0;

        if (n & 1) {
            int q = (n + 1) / 2;
            for (int i = q; i < n; ++i) {
                ans[ptr++] = i;
            }

            for (int i = 0; i < q; ++i) {
                ans[ptr++] = i;
            }
        } else {
            ans[ptr++] = 0;
            int q = (n + 1) / 2 + 1;
            for (int i = q; i < n; ++i) {
                ans[ptr++] = i;
            }

            for (int i = 1; i < q; ++i) {
                ans[ptr++] = i;
            }
        }

        return ans;
    }

    sort(Ap + 1, Ap + n + 1, [&](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 = abs(n - 2 * ptr + 2 * i + 2);

        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;
}
