#include "partition.h"
#include <algorithm>
#include <iostream>
#include <random>
#include <chrono>
#include <queue>

using namespace std;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

vector<int> solve(vector<int> a) {
    int n = a.size();
    if(n == 1) {
        return {0};
    }

    vector<int> idx(n), viz(n);
    long long sum = 0;
    for(int i = 0; i < n; i++) {
        idx[i] = i;
        sum += a[i];
    }

    vector<int> x, y;
    for(int i = 1; i < n; i += 2) {
        if(a[idx[i - 1]] < a[idx[i]]) {
            x.push_back(idx[i - 1]);
            y.push_back(idx[i]);
        } else {
            y.push_back(idx[i - 1]);
            x.push_back(idx[i]);
        }
    }
    if(n % 2 == 1) {
        y.push_back(idx[n - 1]);
    }
    idx.clear();
    for(auto it : x) {
        idx.push_back(it);
    }
    for(auto it : y) {
        idx.push_back(it);
    }
    int cnt = 0;
    long long aux = 0;
    for(int i = n - 1; i >= 0; i--) {
        if(aux < (sum + 1) / 2) {
            aux += a[idx[i]];
            cnt++;
        }
    }
    if(cnt >= (n + 1) / 2) {
        reverse(idx.begin(), idx.end());
        return idx;
    }

    vector<int> answer;
    queue<int> st;
    aux = 0;
    for(int i = 0; i < (n + 1) / 2; i++) {
        answer.push_back(idx[i]);
        viz[idx[i]] = 1;
        aux += a[idx[i]];
        int cate = (n + 1) / 2 - i - 1;
        for(int j = i + 1; j <= n; j++) {
            if(aux >= (sum + 1) / 2) {
                break;
            }
            if((int)st.size() < cate) {
                st.push(idx[j]);
                viz[idx[j]] = 1;
                aux += a[idx[j]];
            } else {
                aux -= a[st.front()];
                viz[st.front()] = 0;
                st.pop();
                aux += a[idx[j]];
                viz[idx[j]] = 1;
                st.push(idx[j]);
            }
        }

        if((int)st.size() == cate && aux >= (sum + 1) / 2) {
            while(!st.empty()) {
                answer.push_back(st.front());
                st.pop();
            }
            for(int j = 0; j < n; j++) {
                if(!viz[j]) {
                    answer.push_back(j);
                }
            }
            return answer;
        }

        while(!st.empty()) {
            viz[st.front()] = 0;
            aux -= a[st.front()];
            st.pop();
        }
    }

    return {-1};
}
