您的位置:首页 > 其它

Uva-536 Tree Recovery

2015-09-10 01:01 519 查看
题目链接:Tree Recovery

题目大意:已知一棵树的先序遍历和中序遍历顺序,求它的后序遍历顺序。

解题思路:关键在于找到父结点的位置,然后递归建树即可。

代码如下:

#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 1e4 + 15;

int rch[maxn], lch[maxn], root;
string Prt, In, s;

void Init(){
    memset(lch, 0, sizeof lch);
    memset(rch, 0, sizeof rch);
}

void Build(const string& a, const string& b){
    if(a.size() <= 1 || b.size() <= 1)
        return;
    int rt = b[0];
    auto it = find(a.begin(), a.end(), rt);
    string la(a.begin(), it); ++it;
    string ra(it, a.end());
    int l = la.size(), r = ra.size();
    string lb(b.begin() + 1, b.begin() + l + 1);
    string rb(b.begin() + l + 1, b.begin() + l + r + 1);
    if(!lb.empty()) lch[rt] = lb[0]; 
    if(!rb.empty()) rch[rt] = rb[0];
    Build(la, lb);
    Build(ra, rb);
}

void Print(int u){
    if(lch[u] > 0) 
        Print(lch[u]);
    if(rch[u] > 0) 
        Print(rch[u]);
    cout << (char)u;
    return;
}

int main(){
    ios::sync_with_stdio(false);
    #ifdef LOCAL
    freopen("in.txt", "r", stdin);
    #endif
    while(getline(cin, s)){
        Init();
        stringstream ss(s);
        ss >> Prt; ss >> In;
        root = Prt[0];
        Build(In, Prt);
        Print(root);
        cout << endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: