Time limit: 3.000 seconds
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=104&page=show_problem&problem=489
You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.
3 2 1 4 5 7 6 3 1 2 5 6 7 4 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 255 255
1 3 255
把建树和DFS两步合并,详见代码。
完整代码:
/*0.086s*/ #include<cstdio> #include<algorithm> using namespace std; int in[10010], post[10010], min_sum, ans; void dfs(int n, int* in, int* post, int sum) { if (n <= 0) return; int p = find(in, in + n, post[n - 1]) - in; sum += post[n - 1]; if (n == 1) { if (sum < min_sum) { min_sum = sum; ans = post[n - 1]; } ///you should output the value of the leaf node of a path of least value. else if (sum == min_sum) ans = min(ans, post[n - 1]); ///In the case of multiple paths of least value you should pick the one with the least value on the terminal node. return; } dfs(p, in, post, sum);///左子树 dfs(n - p - 1, in + p + 1, post + p, sum);///右子树 } int main() { char ch; int n, i; while (~scanf("%d%c", &in[0], &ch)) { if (ch == 10)///只读了一个数(就换行了) { scanf("%d", &post[0]); printf("%d\n", post[0]); continue; } n = 1; while (scanf("%d%c", &in[n++], &ch), ch != 10) ; for (i = 0; i < n; ++i) scanf("%d", &post[i]); ans = min_sum = -1u >> 1; dfs(n, in, post, 0); printf("%d\n", ans); } return 0; }