Submission #1125091

#TimeUsernameProblemLanguageResultExecution timeMemory
1125091PanndaWeird Numeral System (CCO21_day1problem2)C++20
0 / 25
955 ms1114112 KiB
#include <bits/stdc++.h>
using namespace std;

int K, Q, D, M;
vector<int> digits;

constexpr int IMPOSSIBLE = 6785;
constexpr int NOT_CALCULATED = -6785;
constexpr int C = (int)1e6;
map<long long, int> par;
vector<int> parr(C, NOT_CALCULATED);

bool backtrack(long long n) {
    if (n < C) {
        if (parr[n] != NOT_CALCULATED) return parr[n] != IMPOSSIBLE;
    } else {
        if (par.count(n)) return par[n] != IMPOSSIBLE;
    }
    for (int d : digits) {
        if ((n - d) % K == 0 && backtrack((n - d) / K)) {
            n < C ? parr[n] = d : par[n] = d;
            return true;
        }
    }
    n < C ? parr[n] = IMPOSSIBLE : par[n] = IMPOSSIBLE;
    return false;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> K >> Q >> D >> M;
    digits.resize(D);
    for (int i = 0; i < D; i++) {
        cin >> digits[i];
    }
    for (int d : digits) {
        par[d] = d;
    }

    while (Q--) {
        long long N;
        cin >> N;

        if (!backtrack(N)) {
            cout << "IMPOSSIBLE\n";
        } else {
            vector<int> ans;
            do {
                int d = N < C ? parr[N] : par[N];
                ans.push_back(d);
                N = (N - d) / K;
            } while (N != 0);
            for (int i = ans.size() - 1; i >= 0; i--) {
                cout << ans[i] << " \n"[i == 0];
            }
        }

    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...