uva548Tree


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.
Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal
sequences of that tree. Your program will read two line (until end of file) from the input file. The first
line will contain the sequence of values associated with an inorder traversal of the tree and the second
line will contain the sequence of values associated with a postorder traversal of the tree. All values
will be different, greater than zero and less than 10000. You may assume that no binary tree will have
more than 10000 nodes or less than 1 node.
Output
For each tree description you should output the value of the leaf node of a path of least value. In the
case of multiple paths of least value you should pick the one with the least value on the terminal node.
    Sample Input
    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
    Sample Output
    1
    3
    255
テーマ:
二叉木の中序遍歴と後序遍歴を1本あげて、根から葉の結点までの経路が最も短い葉の結点を探して、複数の経路が合っている場合は、葉の結点の最小の結点を選択します.
しかし題意は2回見間違えた....1回目は最小値の葉の結点しか探していないと思って、2回目は1回目に現れる最短経路を選ぶと思っていました....注意後で問題を見るときはinput,outputで問題の意味を推測しないでください.前言を理解した上で、問題を見ます.テーマを間違えたらほほほ.
考え方:
問題は結果を解くことだけを要求するので,実際に木を建てる必要はなく,シミュレーション木を建てるだけでよいため,2つの変数p 1,p 2で後順に遍歴する木の左右の境界を制限し,in 1,in 2で中順遍歴木の左右の境界を制限し,もう1つの変数pathで通過ノードの値を保存する.1つの大木を2つの左右の子の木に割って(pathを更新します)、、、、、、ずっと私に割って、、、、、、、、、、1つの枝しか残っていないまで割って、やっとそれを最短の経路と比較します.
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<sstream>

using namespace std;

const int inf = 0x3f3f3f3f;
int inorder[10004], n, ans, minn;
int postorder[10004];

void build(int pl, int pr, int inl, int inr, int path)
{
	if (pl > pr)
		return;
	if (pl == pr)
	{
		if (path + postorder[pl] <= minn)
		{
			if (path + postorder[pl] == minn)
			{
				ans = ans < postorder[pl] ? ans : postorder[pl];
			}
			else
			{
			    minn = path + postorder[pl];
		    	ans = postorder[pl];
			}
		}
		return;
	}
	int fir = postorder[pr];
	for (int i = inl; i <= inr; ++i)
	{
		if (inorder[i] == fir)
		{
				build(pl, pl + i - inl - 1, inl, i - 1, path + inorder[i]);
				build(pr - (inr - i), pr - 1, i + 1, inr, path + inorder[i]);
				break;
		}
	}
}

int main()
{
	memset(inorder, 0, sizeof(inorder));
	memset(postorder, 0, sizeof(postorder));
	string s;
	while (getline(cin, s))
	{
		if (s.size() == 0)
			break;
		stringstream st(s);
		n = -1;
		while (st >> inorder[++n])
			;
		getline(cin, s);
		stringstream str(s);
		int cn = 0;
		ans = inf;
		minn = inf;
		while (str >> postorder[cn++])
			;
		build(0, n - 1, 0, n - 1, 0);
		cout << ans << endl;
	}
}