利用中序和后序构建二叉树然后进行dfs搜索,两步可以同时进行,另外这道题目输入处理也有点麻烦,参考了一些大神的代码,自己重写因为一个值每次case之后未初始化悲剧的RE了好多次。
查了下 runtime error的可能大概有:
Runtime Error(ARRAY_BOUNDS_EXCEEDED) // array bounds exceed 数组越界
Runtime Error(DIVIDE_BY_ZERO) //divisor is nil 除零
Runtime Error(ACCESS_VIOLATION) //illegal memory access 非法内存读取
Runtime Error(STACK_OVERFLOW) //stack overflow 系统栈过载
#include<stdio.h>
int in[10010];
int post[10010];
int minSum;
int res;
int findIndex(int key, int*array, int n) {
int i;
for (i = 0; i < n; i++) {
if (array[i] == key)
return i;
}
return -1;
}
void dfs(int n, int*in, int*post, int sum) {
if (n <= 0)
return;
int root = post[n - 1];
if (n == 1) {
int tmpSum = sum + root;
if (tmpSum < minSum) {
minSum = tmpSum;
res = root;
} else if (tmpSum == minSum)
res = res < root ? res : root;
return;
}
int index = findIndex(post[n - 1], in, n);
dfs(index, in, post, sum + root);
dfs(n - index - 1, in + index + 1, post + index, sum + root);
}
int main() {
/* setbuf(stdout,NULL);*/
char ch;
int i, n;
while (scanf("%d%c", &in[0], &ch) != EOF) {
minSum = 0x7fffffff;
res = 0x7fffffff;
if (ch == '\n') {
scanf("%d", &post[0]);
printf("%d\n", post[0]);
continue;
}
n = 1;
while (scanf("%d%c", &in[n++], &ch)) {
if (ch == '\n')
break;
}
for (i = 0; i < n; i++)
scanf("%d", &post[i]);
dfs(n, in, post, 0);
printf("%d\n", res);
}
return 0;
}
495

被折叠的 条评论
为什么被折叠?



