UVa 548
题意:给中序,后序,然后还原二叉树,再输出从root到leaf节点中节点和最小的那个leaf很无语的是用index这个变量,居然被判了个CE。。。
#include
<
stdio.h
>
#include < string .h >
struct Node
{
int l, r, v;
};
char ch;
int inorder[ 10100 ], postorder[ 10100 ];
Node node[ 10100 ];
int sz, minn, indexn;
void recover( int inl, int inr, int postl, int postr, int & fa)
{
if ( inr < inl || postr < postl )
return ;
int p = ++ sz;
fa = sz;
node[p].v = postorder[postr];
int k;
for ( k = inl ; k <= inr && inorder[k] != postorder[postr] ; k ++ );
int len = k - inl;
recover(inl, k - 1 , postl, postl + len - 1 , node[p].l);
recover(k + 1 , inr, postl + len, postr - 1 , node[p].r);
}
void dfs( int p, int num)
{
if ( ! node[p].l &&! node[p].r)
{
if ( node[p].v + num < minn )
{
indexn = node[p].v;
minn = node[p].v + num;
}
else if ( node[p].v + num == minn )
if ( indexn > node[p].v)
indexn = node[p].v;
return ;
}
node[p].v += num;
if (node[p].l)
dfs(node[p].l, node[p].v);
if (node[p].r)
dfs(node[p].r, node[p].v);
}
int main()
{
while ( EOF != scanf( " %d%c " , inorder, & ch) )
{
indexn = minn = ~ 1u >> 1 ;
memset(node, 0 , sizeof (node));
int top;
for ( top = 1 ; ch != ' \n ' ; top ++ )
scanf( " %d%c " , inorder + top, & ch);
for ( int i = 0 ; i < top ; i ++ )
scanf( " %d " , postorder + i);
recover( 0 , top - 1 , 0 , top - 1 , node[sz = 0 ].r);
dfs( 1 , 0 );
printf( " %d\n " , indexn);
}
return 0 ;
}
#include < string .h >
struct Node
{
int l, r, v;
};
char ch;
int inorder[ 10100 ], postorder[ 10100 ];
Node node[ 10100 ];
int sz, minn, indexn;
void recover( int inl, int inr, int postl, int postr, int & fa)
{
if ( inr < inl || postr < postl )
return ;
int p = ++ sz;
fa = sz;
node[p].v = postorder[postr];
int k;
for ( k = inl ; k <= inr && inorder[k] != postorder[postr] ; k ++ );
int len = k - inl;
recover(inl, k - 1 , postl, postl + len - 1 , node[p].l);
recover(k + 1 , inr, postl + len, postr - 1 , node[p].r);
}
void dfs( int p, int num)
{
if ( ! node[p].l &&! node[p].r)
{
if ( node[p].v + num < minn )
{
indexn = node[p].v;
minn = node[p].v + num;
}
else if ( node[p].v + num == minn )
if ( indexn > node[p].v)
indexn = node[p].v;
return ;
}
node[p].v += num;
if (node[p].l)
dfs(node[p].l, node[p].v);
if (node[p].r)
dfs(node[p].r, node[p].v);
}
int main()
{
while ( EOF != scanf( " %d%c " , inorder, & ch) )
{
indexn = minn = ~ 1u >> 1 ;
memset(node, 0 , sizeof (node));
int top;
for ( top = 1 ; ch != ' \n ' ; top ++ )
scanf( " %d%c " , inorder + top, & ch);
for ( int i = 0 ; i < top ; i ++ )
scanf( " %d " , postorder + i);
recover( 0 , top - 1 , 0 , top - 1 , node[sz = 0 ].r);
dfs( 1 , 0 );
printf( " %d\n " , indexn);
}
return 0 ;
}