#include <bits/stdc++.h>
#include "books.h"
#define tiii tuple<int,int,int>
#define int long long
using namespace std;
//
// --- Sample implementation for the task books ---
//
// To compile this program with the sample grader, place:
//     books.h books_sample.cpp sample_grader.cpp
// in a single folder and run:
//     g++ books_sample.cpp sample_grader.cpp
// in this folder.
//
void solve(int32_t n, int32_t K, long long A, int32_t S) {
    vector<int> arr(n);
    for(int i = 0; i < n; i++){
        arr[i] = skim(i+1);
    }
    vector<int32_t> chose(K);
    int sum = 0;
    for(int i = 0; i < K; i++){
        chose[i] = i;
        sum += arr[i];
    }
    if(sum > 2*A) {
        impossible();
    }
    priority_queue<tiii> pq;
    for(int i = 0; i < K; i++){
        tiii choice = {-1,i,-1};
        
        for(int j = 0; j < n; j++){
            if(find(chose.begin(),chose.end(), j) != chose.end()) continue;
            int del = -arr[chose[i]]+arr[j];
            if(sum+del > 2*A || del <= 0) continue;
            choice = max(choice, {del, i, j});
        } 
        pq.push(choice);
    }
    while(pq.size() && sum < A){
        int delta, old, nxt;
        tie(delta,old,nxt) = pq.top(); pq.pop(); 
        if(arr[nxt]-arr[chose[old]] != delta || find(chose.begin(),chose.end(),nxt) != chose.end()){
            // reevaluate
            tiii choice = {-1,old,-1}; 
        
            for(int j = 0; j < n; j++){
                if(find(chose.begin(),chose.end(), j) != chose.end()) continue;
                int del = -arr[chose[old]]+arr[j];
                if(sum+del > 2*A || del <= 0) continue;
                choice = max(choice, {del, old, j});
            } 
            pq.push(choice);
            continue;
        }
        int oind = chose[old];
        chose[old] = nxt;
        sum += delta; 
        // this element may be reinserted
        tiii choice = {-1,old,-1}; 
        
        for(int j = 0; j < n; j++){
            if(find(chose.begin(),chose.end(), j) != chose.end()) continue;
            int del = -arr[chose[old]]+arr[j];
            if(sum+del > 2*A || del <= 0) continue;
            choice = max(choice, {del, old, j});
        } 
        pq.push(choice);
    }
    if(sum < A){
        impossible();
    }else{
        for(int i = 0; i < K; i++) chose[i]++;
        answer(chose);
    }
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |