这题在于分治法的利用
#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); }
时间: 2024-11-03 21:02:48