Ultraviolet A 10821-constructing BST
Question Link
With a 1-N number, you must construct a BST with a height not greater than H and have the smallest Lexicographic Order. The output sequence
Idea: greedy construction. Since the Lexicographic Order is the smallest, the root of each subtree should be as small as possible, that is, the right subtree should be filled up as much as possible. Follow this policy to construct DFS.
Code:
# Include <cstdio> # include <cstring> # include <algorithm> using namespace STD; int N, H; void DFS (int s, int N, int H) {If (H = 0 | n = 0) return; int TMP = max (0, N-(1 <(h-1 ))); printf ("% d", S + TMP + 1); DFS (S, TMP, h-1); DFS (S + TMP + 1, n-TMP-1, h-1);} int main () {int CAS = 0; while (~ Scanf ("% d", & N, & H) & N | h) {printf ("case % d:", ++ CAS ); if (1 <H)-1 <n) {printf ("impossible. \ n "); continue;} DFS (0, N, H); printf (" \ n ");} return 0 ;}
Ultraviolet A 10821-constructing BST (Greedy Construction)