Pagini recente » Cod sursa (job #2956724) | Cod sursa (job #594514) | Cod sursa (job #1366561) | Cod sursa (job #27516) | Cod sursa (job #2751732)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("planeta.in");
ofstream fout("planeta.out");
long long Catalan[31], H[31][31]; // It follows that Cn is the number of full binary trees with n + 1 leaves - wiki
long long N, K;
void generateCatalan(long long N)
{
Catalan[0] = 1;
for (long long n =0; n <= N; ++n)
for (long long i = 0; i <= n; ++i)
{
H[n][i] = Catalan[i - 1] * Catalan[n - i];
// for n there's H[n][i] BST's starting with i
Catalan[n + 1] += Catalan[i]*Catalan[n - i];
}
}
void solve(long long N, long long K, long long a)
{
if (N == 0) return;
long long sum = 0, last_sum;
for (long long i = 1; i <=N; ++i)
{
last_sum = sum;
sum += H[N][i]; // for current N we found sum nr. of BST so far
if (last_sum < K && sum >=K) // if the K'th preorder was found
{
fout << i + a << " "; // it means it starts with i + the aux
long long aux_K = K - last_sum;
long long left_nr_pre = aux_K/Catalan[N - i];
if (aux_K % Catalan[N - i] != 0)
left_nr_pre ++;
long long right_nr_pre = aux_K % Catalan[N - i];
if (right_nr_pre == 0)
right_nr_pre = Catalan[N - i];
solve(i - 1, left_nr_pre, a); // searching for the left node in the preorder
solve(N - i, right_nr_pre, i + a); // searching for the right node in the preorder
// i + a => we'll replace the numbers from the right subtree
// bc it's the same thing as generating the subtrees with
// 1, 2, 3, 4 as with 4, 5, 6, 7 => a = 3
break;
}
}
}
int main()
{
fin >> N >> K;
generateCatalan(N);
/*
for (long long i = 0; i <= N; ++i)
{
for (auto j = 0; j <= N; ++j)
cout << H[i][j] << " ";
cout << endl;
}
*/
solve(N, K, 0);
return 0;
}