#include "partition.h"
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

using namespace __gnu_pbds;
using namespace std;

using ll = long long;

vector<int> solve(vector<int> a) {

    vector<int> x;
    int n = (int)a.size();
    unordered_map<int, int> mp, cnt;

    vector<int> g(n);
    for(int i = 0; i < n; i++) {
        g[i] = mp[a[i]] - 1;
        mp[a[i]] = i + 1;
        cnt[a[i]]++;
    }
    a.clear();
    for(auto [w, y] : cnt) {
        for(int i = 0; i < y; i++) a.push_back(w);
    }
    for(auto [w, y] : mp) {
        int st = y - 1;
        while(st > -1) {
            x.push_back(st);
            st = g[st];
        }
    }
    vector<ll> suff;
    suff.push_back(0ll);
    ll sm = 0;
    for(int i = n - 1; i >= 0; i--) {
        sm += a[i];
        suff.push_back(sm);
    }
    vector<ll> pref(n);
    for(int i = 0; i < n; i++) pref[i] = (i == 0 ? 0 : pref[i - 1]) + a[i];
    ll tar = pref[n - 1] / 2;
    int sz = (n + 1) / 2;
    for(int i = sz - 1; i >= 0; i--) {
        if(pref[i] + suff[sz - (i + 1)] > tar) {
            vector<int> res;
            for(int j = 0; j <= i; j++) {
                res.push_back(x[j]);
            }
            int L = (n - (sz - (i + 1)));
            for(int j = L; j < n; j++) {
                res.push_back(x[j]);
            }
            for(int j = i + 1; j < L; j++) {
                res.push_back(x[j]);
            }
            return res;
        }
    }
    vector<int> res;
    int L = (n - sz);
    for(int j = L; j < n; j++) {
        res.push_back(x[j]);
    }
    for(int j = 0; j < L; j++) res.push_back(x[j]);
    return res;


}
