您的位置:首页 > 其它

【USACO3.4.2】美国血统

2015-04-07 21:30 232 查看
这个…… 就是给树的前序中序遍历,求后序。

没啥好说的啊…… 任何一本书上都有讲解的

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int zhong[100]={0}, qian[100]={0};
int zuo[100]={0}, you[100]={0};
int len;
char s[100];

void init()
{
gets(s);
len = strlen(s);
for (int i = 0; i != len; ++ i)
zhong[i + 1] = s[i] - 'A' + 1;
gets(s);
for (int i = 0; i != len; ++ i)
qian[i + 1] = s[i] - 'A' + 1;
}

int p = 0;

int cal(int L, int R)
{
if (L > R) return 0;
++ p;
int tmp;
for (int i = L; i <= R; ++ i)
if (zhong[i] == qian[p])
{
tmp = i;
break;
}
int zhi = qian[p];
zuo[zhi] = cal(L, tmp - 1);
you[zhi] = cal(tmp + 1, R);
return zhi;
}

void through(int now)
{
if (zuo[now]) through(zuo[now]);
if (you[now]) through(you[now]);
cout<< (char)(now + 'A' - 1);
}

void doit()
{

through(cal(1, len));
cout<<endl;
}

int main()
{
init();
doit();
return 0;
}
/*

ABEDFCHG
CBADEFGH

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: