USACO American Heritage 解题报告

来源:互联网 发布:长沙知豆电动汽车租赁 编辑:程序博客网 时间:2024/05/01 22:37

这道题是给了树的中序遍历和前序遍历,求后序遍历。

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

/* 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-orderchar 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;  } 


原创粉丝点击