现在可以进行两种操作:
1.将一个数,从操作数序列的头端移到栈的头端(对应数据结构栈的 push 操作)
2.将一个数,从栈的头端移到输出序列的尾端(对应数据结构栈的 pop 操作)
你的程序将对给定的 n,计算并输出由操作数序列 1,2,…,n 经过操作可能得到的输出序列的总数。
很显然这是一道递推题,两种思路来做
1.如果能一眼看出来这是卡特兰数的话,直接用卡特兰数做就行了
#includeusing namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + ch - 48; ch = getchar(); } return x * f; } long long n; long long f[20]; int main() { n = read(); f[0] = f[1] = 1; f[2] = 2; for (register int i(3); i <= n; i = -~i) { for (register int j(0); j < i; j = -~j) { f[i] += f[j] * f[i - 1 - j]; } } printf("%lld", f[n]); return 0; }
2.根据题目给的条件进行递推
设f[i][j]表示有i个数未输出,j个数未入栈,显然,当j=0的时候,只能按顺序出栈,f[i][j] = 1;
当j≠0时,若选择弹出栈中的数,有f[i-1][j]种可能,若选择将一个数压进栈,有f[i][j-1]种可能
于是递推式:f[i][j] = f[i-1][j] + f[i][j-1]
#includeusing namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + ch - 48; ch = getchar(); } return x * f; } long long n; long long f[20][20]; int main() { n = read(); for (register int i(1); i <= n; i = -~i) f[i][0] = 1; for (register int i(1); i <= n; i = -~i) { for (register int j(1); j <= i; j = -~j) { f[i][j] = f[i - 1][j] + f[i][j - 1]; } } printf("%lld", f[n][n]); return 0; }



