出栈序列
给定正整数 n,编程计算左边轨道车皮编号依次为 1,2,…,n 时,在右边轨道 最多可 以得到多少个不同的车皮编序方案。 例如当 n=3 时,最多得到 5 组不同的编序方 案如下:
123
132
213
231
321
思路:对于一个栈来进行搜索回溯操作,栈有内容时可以进行入栈和出栈两次操作,否则只入栈。注意回溯还原栈的内容时,应从输出队列中拿上一个回来,而不是只是单纯地移动游标,因为根据搜索地流程,上一个que的内容可能不等于stk[top+1];实际上输出的个数可被证明是一个卡特兰数
Code:
#include <iostream>
using namespace std;
const int maxn = (int)1e5+5;
#define repU(i, a, b) for (int i = a; i <= b; i++)
#define repD(i, a, b) for (int i = a; i >= b; i--)
int n;
int stk[maxn], top = -1;
int que[maxn], tail = 0;
//对于栈每次有两次操作 push pop
int dfs (int idx) {
if (idx == n) {
repU(i, 0, tail-1) printf("%d ", que[i]);
repD(i, top, 0) printf("%d ", stk[i]);
putchar('\n');
return 1;
}
int cnt = 0;
if (top != -1) { //pop
que[tail++] = stk[top--];
cnt += dfs(idx);
stk[++top] = que[--tail];
/* 注意区别
top++;
tail--;
*/
}
stk[++top] = idx+1;
cnt += dfs(idx+1);
top--;
return cnt;
}
int main() {
while (scanf("%d", &n)) {
printf("count = %d\n", dfs(0));
system("pause");
}
return 0;
}