码迷,mamicode.com
首页 > 其他好文 > 详细

Tree Traversals Again (25)

时间:2015-06-07 18:43:09      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

这题在于分治法的利用

#include <iostream>
#include <string>
#include <stack>
using namespace std;

void fun(int *pre, int *mid, int len, int * result);
int main()
{
    int n;
    int *a, *b;
    int x = 0, top = 0, y = 0;
    stack<int> S;

    cin >> n;
    a = (int*)malloc(n*sizeof(int));
    b = (int*)malloc(n*sizeof(int));
    for (int i = 0; i < 2 * n; i++){
        string str;
        cin >> str;
        if (str == "Push"){
            cin >> a[x];
            S.push(a[x]);
            x++;
        }
        else{
            b[y] = S.top();
            S.pop();
            y++;
        }
    }

    int *result = (int *)malloc(n*sizeof(int));
    fun(a, b, n,result);


    cout << result[0];
    for (int i = 1; i < n; i++){
        cout << " " << result[i];
    }

}
void fun(int *pre, int *mid, int len,int * result)
{
    if (len == 0){
        return;
    }
    if (len == 1){
        result[0] = pre[0];
        return;
    }
    int p = pre[0];
    result[len - 1] = p;

    int i;
    for (i = len - 1; i >= 1; i--){
        if (mid[i] == p){
            break;
        }
    }
    fun(pre + 1, mid, i, result);
    fun(pre + 1 + i, mid + 1 + i, len - 1 - i, result + i);
}

 

Tree Traversals Again (25)

标签:

原文地址:http://www.cnblogs.com/zhouyiji/p/4558712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!