#include "souvenirs.h"
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
template<typename T>
bool assign_min(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<typename T>
bool assign_max(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
int n;
vector<bool> seen;
vector<ll> p, cnt;
vector<pair<vector<int>, ll>> eqs;
void dfs(vector<int> &v, ll s) {
    eqs.push_back({v, s});
    for (auto x : v) cnt[x]++;
    if ((int) v.size() == 1) {
        p[v[0]] = s;
        if (seen[v[0]] || v[0] == n - 1) {
            return;
        }
        seen[v[0]] = 1;
        p[v[0]] = s;
        pair<vector<int>, ll> t = transaction(s - 1);
        dfs(t.first, s - 1 - t.second);
        return;
    }
    pair<vector<int>, ll> t = transaction(s / (int) v.size());
    dfs(t.first, s / (int) v.size() - t.second);
}
void buy_souvenirs(int nn, ll p0) {
    n = nn;
    seen.resize(n);
    cnt.resize(n);
    p.resize(n);
    p[0] = p0;
    pair<vector<int>, ll> t = transaction(p0 - 1);
    dfs(t.first, p0 - 1 - t.second);
    sort(eqs.begin(), eqs.end(), [&](auto a, auto b) {
        return a.first[0] < b.first[0];
    });
    for (auto [v, s] : eqs) {
        vector<int> nw;
        ll rem = s;
        for (auto x : v) {
            if (p[x] == 0) {
                nw.push_back(x);
            } else {
                rem -= p[x];
            }
        }
        if (nw.size() == 1) {
            p[nw[0]] = rem;
        } else {
            eqs.push_back({nw, rem});
        }
    }
    for (int i = 0; i < n; i++) {
        while (cnt[i] < i) {
            transaction(p[i]);
            cnt[i]++;
        }
    }
}
| # | 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... |