Question link:
Http://uva.onlinejudge.org/index.php? Option = com_onlinejudge & Itemid = 8 & page = show_problem & problem = 653
Question meaning:
To give a binary tree, each layer has a value, 1 to the right, left to the left, give you a string of values for each layer, let you find the final result.
Solution:
Remember the hierarchy of the tree, and remember the values represented by XI in the tree. Note that the final result of the search is: multiply the value to the right by 2 and multiply the value to the left by 2 minus 1, returns the subscript of the final result.
Code:
# Include <iostream> # include <cmath> # include <cstdio> # include <cstdlib> # include <string> # include <cstring> # include <algorithm> # include <vector> # include <map> # include <stack> # include <queue> # define EPS 1e-6 # define Inf (1 <20) # define PI ACOs (-1.0) using namespace STD; char save [10]; int result [150], tree [10], path [10]; int ans [150]; int main () {int CA = 0, n, m; while (scanf ("% d", & N) {for (INT I = 1; I <= N; I ++) {scanf ("% s", save); sscanf (& save [1], "% d", & tree [I]); // remember the number of each layer} int Limit = (INT) (POW (2.0, N * 1.0) + EPS); For (INT I = 1; I <= limit; I ++) scanf ("% 1D", & Result [I]); // remember the final result set scanf ("% d ", & M); printf ("s-tree # % d: \ n", ++ CA); For (INT I = 1; I <= m; I ++) {for (Int J = 1; j <= N; j ++) scanf ("% 1D", & path [J]); // The Int last = 1, depth = 1 for each serial number; while (depth <= N) {If (path [tree [depth]) // here is the key, if it is 1, multiply by 2; otherwise multiply by 2 minus 1 last = last * 2; else last = last * 2-1; depth ++;} printf ("% d ", result [last]); // The final result} printf ("\ n");} return 0 ;}