您的位置:首页 > 其它

USACO American Heritage 解题报告

2013-10-27 10:00 429 查看
这道题是给了树的中序遍历和前序遍历,求后序遍历。

我的解法中有大量的字符串合并操作,实际上完全不需要,直接输出字符即可。

/*
ID: thestor1
LANG: C++
TASK: heritage
*/
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cassert>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

string tree(int lin, int rin, int lpre, int rpre, string in, string pre)
{
// cout<<lin<<", "<<rin<<", "<<lpre<<", "<<rpre<<", "<<in<<", "<<pre<<endl;
if(lin > rin)
{
return "";
}
if(lin == rin)
{
return string(1, in[lin]);
}
int root = lin;
// cout<<lpre<<":"<<pre[lpre]<<endl;
while(in[root] != pre[lpre] && root <= rin)
{
root++;
}
assert(root <= rin);
int left = root - 1 - lin + 1;
// cout<<"root: "<<root<<", left: "<<left<<endl;
return tree(lin, root - 1, lpre + 1, lpre + 1 + left - 1, in, pre) + tree(root + 1, rin, lpre + left + 1, rpre, in, pre) + string(1, in[root]);
}

int main()
{
FILE *fin  = fopen ("heritage.in", "r");
FILE *fout = fopen ("heritage.out", "w");
//in-order
char buff[27];
fscanf(fin, "%[^\n]%*c", buff);
string in(buff);
fscanf(fin, "%[^\n]%*c", buff);
string pre(buff);

int n = in.length();
string post;
post.reserve(n);
post = tree(0, n - 1, 0, n - 1, in, pre);
// cout<<post<<endl;
fprintf(fout, "%s\n", post.c_str());
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: