A1138 | 根据前序、中序生成后序

参考了博客上码量不到50行的代码,完成了这题的AC重构。感觉真的基础很重要,这题其实是很简单的一道树的前中后序的题目。但是我之前练习的时候,都是用的自己总结的骚套路,虽然理解起来很直观,但是用了动态数组(vector),时间复杂度比较大。这题问题规模n=5e4,时间控制600ms,虽然已经AC了,但是运行时间也花了400ms。

当时考试的时候又是用vector又是建树,所以最后一个case没过,丢了5分,很可惜。

#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>


#define I scanf
#define OL puts
#define O printf
#define F(a,b,c) for(a=b;a<c;a++)
#define FF(a,b) for(a=0;a<b;a++)
#define FG(a,b) for(a=b-1;a>=0;a--)
#define LEN 50000
#define MAX 0x06FFFFFF

using namespace std;

int in[LEN];
int pre[LEN];
int post[LEN];
int t=0;
void setPost(int ps,int pe,int is,int ie);

int main() {
    freopen("d:/input/A1138.txt","r",stdin);
    int n;
    scanf("%d",&n);
    int i;
    FF(i,n) scanf("%d",&pre[i]);
    FF(i,n) scanf("%d",&in[i]);
    setPost(0,n-1,0,n-1);
    O("%d
",post[0]);
    return 0;
}

void setPost(int ps,int pe,int is,int ie){
    if(ps>pe)return;//null
    if(ps==pe){
        post[t++]=pre[ps];
    }else{
        //find the elem is the pair of preOrder (ps)
        int i=is;
        while(in[i]!=pre[ps] && i<ie) i++;//redirect
        //left
        setPost(ps+1, ps+i-is, is, i-1);
        //right
        setPost(ps+i-is+1, pe, i+1, ie);
        //root
        post[t++]=pre[ps];
    }
}
View Code

需要注意的点:

  根据问题的规模和题目的条件,估计应该用什么方法,越简单越好,题目不涉及的边界条件就不要去管了。

需要拓展的点:

  1.深化树的前中后序遍历。

  2.根据问题规模估算时间复杂度。

原文地址:https://www.cnblogs.com/TQCAI/p/8059718.html