Cod sursa(job #3326286)

Utilizator mihai_spartanulMihai Lucescu Dimitrie mihai_spartanul Data 27 noiembrie 2025 23:32:22
Problema Dusman Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;

int n, K, m;
bool dusman[1001][1001];
bool folosit[1001];
int sol[1001];

long long count_perm(int last, int rem) {
    // calculează câte permutări valide există cu `rem` poziții rămase
    // limitat la K (max 10000)
    long long c = 1;
    for (int i = 2; i <= rem; i++) {
        c = c * i;
        if (c > K) return K + 1; // nu avem nevoie de mai mult
    }
    return c;
}

int main() {
    ifstream cin("dusman.in");
    ofstream cout("dusman.out");

    cin >> n >> K >> m;
    for (int i = 1; i <= m; i++) {
        int a, b;
        cin >> a >> b;
        dusman[a][b] = dusman[b][a] = true;
    }

    for (int pos = 1; pos <= n; pos++) {
        for (int cand = 1; cand <= n; cand++) {
            if (folosit[cand]) continue;

            if (pos > 1 && dusman[cand][sol[pos - 1]]) continue;

            folosit[cand] = true;

            int rem = n - pos;
            long long ways = count_perm(cand, rem);

            if (ways >= K) {
                sol[pos] = cand;
                break;
            } else {
                K -= ways;
                folosit[cand] = false;
            }
        }
    }

    for (int i = 1; i <= n; i++)
        cout << sol[i] << " ";
    cout << "\n";

    return 0;
}