uva 548 - Tree

利用中序和后序构建二叉树然后进行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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值