Editorial for A Message to the Underworld


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.
#include <bits/stdc++.h>

#define ll long long

using namespace std;




vector<ll> merge(vector<ll>& v1, vector<ll>& v2) {
    vector<ll> merged;

    int i=0,j=0;

    while (i<v1.size()&&j<v2.size()){
        if (v1[i]<=v2[j]){
            merged.push_back(v1[i]);
            i++;
        } else {
            merged.push_back(v2[j]);
            j++;
        }
    }

    while (i < v1.size()) {
        merged.push_back(v1[i]);
        i++;
    }
    while (j < v2.size()) {
        merged.push_back(v2[j]);
        j++;
    }

    return merged;
}


int n,k;

int main() {
    cin>>n>>k;
    assert(2<=n && n<=100000);
    assert(2<=k && k<=100);
    vector<ll> arr(n), current; 
    for(int i=0;i<n;i++){
        cin>>arr[i];
        assert(1<=arr[i] && arr[i]<=1000000000LL);
    }

    if(n>((long long)(1)<<std::min(30,k))){          //2^k check
        cout<<-1<<endl;
        return 0; 
    }

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




    for (int len=0;len<k;len++){
        current=merge(current,arr); //O(n)
        int index=0;
        for (int i=0;i+1<current.size();i+=2,index++){  //O(n)
            current[index]=current[i]+current[i+1];
        }
        current.resize(index);
        // for(auto i: current)cout<<i<<" ";
        // cout<<endl;
    }




    n--;
    ll res = 0;
    while(n){
        int index=0,start=0;
        if(n%2==1) {
            start = 1;              //because starting element gets used
            // cout<<"||"<<current[0]<<"||"<<endl;
            res += current[0];
        }
        for(int i=start;i+1<current.size();i+=2,index++){   //O(n)
            current[index] = current[i] + current[i+1];
        }

        current.resize(index);
        // for(auto i: current)cout<<i<<" ";
        // cout<<endl;
        n>>=1;
    } 
    cout<<res<<endl;
}