【问题描述】
树的凹入表示法主要用于树的屏幕或打印输出,其表示的基本思想是兄弟间等长,一个结点要不小于其子结点的长度。二叉树也可以这样表示,假设叶结点的长度为1,一个非叶结点的长并等于它的左右子树的长度之和。
一棵二叉树的一个结点用一个字母表示(无重复),输出时从根结点开始:
每行输出若干个结点字符(相同字符的个数等于该结点长度),
如果该结点有左子树就递归输出左子树;
如果该结点有右子树就递归输出右子树。
假定一棵二叉树一个结点用一个字符描述,现在给出先序和中序遍历的字符串,用树的凹入表示法输出该二叉树。
【输入格式】
输入文件btout.in共两行,每行是由字母组成的字符串(一行的每个字符都是唯一的),分别表示二叉树的先序遍历和中序遍历的序列。
【输出格式】
输出文件btout.out的行数等于该树的结点数,每行的字母相同。
【输入样例】btout.in
ABCDEFG
CBDAFEG
【输出样例】btout.out
AAAA
BB
C
D
EE
F
G
#include<cstdio>
#include<string>
#include<iostream>
#include<map>
using namespace std;
map<char,char> l,r;
string s1,s2;
int length(char t)
{
int ans=0;
if(l[t]) ans+=length(l[t]);
if(r[t]) ans+=length(r[t]);
if(ans==0) return 1;
return ans;
}
char work(int l1,int r1,int l2,int r2)
{
int m = s2.find(s1[l1]);
if(m>l2) l[s1[l1]]=work(l1+1,l1+m-l2,l2,m-1);
if(m<r2) r[s1[l1]]=work(l1+m-l2+1,r1,m+1,r2);
return s1[l1];
}
int main()
{
freopen("btout.in","r",stdin);
freopen("btout.out","w",stdout);
cin>>s1>>s2;
work(0,s1.length()-1,0,s2.length()-1);
for(int i=0;i<=s1.length()-1;i++)
{
for(int j=1;j<=length(s1[i]);j++)
printf("%c",s1[i]);
printf("\n");
}
}