Cod sursa(job #3135386)

Utilizator TheGodFather2131Alexandru Miclea TheGodFather2131 Data 3 iunie 2023 00:17:17
Problema Planeta Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.09 kb
//ALEXANDRU MICLEA

#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <time.h>
#include <iomanip>
#include <deque>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <stack>
#include <bitset>
#include <random>
#include <chrono>
#include <iostream>
#include <fstream>
#include <array>

using namespace std;

typedef long long ll;

//VARIABLES

long long catalane[35];

//FUNCTIONS

void solve(int nodes, int root, int k) {
    // for a given node, I have nodes amount of nodes left to 
    // plant under me

    // if I have no nodes then I can return
    if (nodes == 0) return;

    // one node left means I just print it and leave
    if (nodes == 1) {
        cout << root << ' ';
        return;
    }

    // get the amount of BST's with given amount of nodes
    for (int i = 1; i <= nodes; i++){
        // lower i means more nodes to the right subtree
        long long p = catalane[i - 1] * catalane[nodes - i];

        // if the product is bigger than my order it means that 
        // somewhere here my solution lies
        if (p >= k) {
            // preorder -> NLR
            cout << (root + i - 1) << ' ';
            solve(i - 1, root, (k - 1) / catalane[nodes - i] + 1);
            solve(nodes - i, root + i, (k - 1) % catalane[nodes - i] + 1);
            return;
        } 
        // else I have reduntant BST's, skip them
        k -= p;
    }
}

//MAIN
int main() {

#ifdef INFOARENA
    ifstream fin("planeta.in"); ofstream fout("planeta.out");
    cin.rdbuf(fin.rdbuf()); cout.rdbuf(fout.rdbuf());
#endif

    catalane[0] = catalane[1] = 1;

    for (int i = 2; i <= 34; i++) {
        for (int j = 1; j <= i; j++) {
            catalane[i] += catalane[j - 1] * catalane[i - j];
        }
    }
    //cout << catalane[5];
    // for (int i = 1; i <= 5; i++) cout << catalane[i] << ' ';

    int n;
    long long k; 
    cin >> n >> k;

    solve (n, 1, k);

    return 0;
}