zoukankan      html  css  js  c++  java
  • POJ

    http://poj.org/problem?id=2255

    题意:给定先序遍历和中序遍历,求后序遍历。

    回忆以前上DataStructure课的时候貌似写过类似的。

    先从先序入手,从左到右扫描,进入时节点时立刻入栈,离开节点时立刻出栈。

    关键是怎么知道什么时候才是立刻节点了呢?

    貌似只有n^2的做法,因为要从中序遍历序列中找根。

    但其实假如预处理出中序遍历的序列中的字母每个指向的位置就不用这额外的时间花费n了。

    也就是从先序遍历入手,进入节点时把根节点的中序遍历序列指针两侧递归下去。

    所以构造的形式如同一棵线段树。

    #include<algorithm>
    #include<cmath>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<map>
    #include<set>
    #include<stack>
    #include<string>
    #include<queue>
    #include<vector>
    using namespace std;
    typedef long long ll;
    
    char s[1005];
    char t[1005];
    int ss[1005];
    int tt[1005];
    char st[1005];
    int top;
    
    void build(int sl, int sr, int tl, int tr) {
        if(tl != tr) {
            int tm = tt[s[sl]];
            if(tm > tl) {
                //左子树还有
                build(sl + 1, sl + tm - tl, tl, tm - 1);
            }
            if(tm < tr) {
                //右子树还有
                build(sl + tm - tl + 1, sl + sr, tm + 1, tr);
            }
        }
        st[++top] = s[sl];
    }
    
    int main() {
    #ifdef Yinku
        freopen("Yinku.in", "r", stdin);
    #endif // Yinku
        while(~scanf("%s%s", s + 1, t + 1)) {
            top = 0;
            int n = strlen(s + 1);
            for(int i = 1; i <= n; ++i) {
                ss[s[i]] = i;
                tt[t[i]] = i;
            }
            build(1, n, 1, n);
            for(int i = 1; i <= n; ++i)
                printf("%c", st[i]);
            printf("
    ");
        }
    }
    

    实现起来的细节还是蛮多的。但本质上是通过dfs序连续这个性质进行分治。

  • 相关阅读:
    Babel:JavaScript编译器
    Webpack:前端资源模块化管理和打包工具
    springboot之RocketMq实现
    spingboot之Java邮件发送
    第一模块总结
    嵌入式面试题(一)
    C/C++练习题(三)
    ToolTip特效 JavaScript 盗取厦门人才网的特效
    C#后台无刷新页面弹出alert方法
    复制表及其只复制表数据的区别
  • 原文地址:https://www.cnblogs.com/Inko/p/11719033.html
Copyright © 2011-2022 走看看