YbtOJ 栈的问题

现在可以进行两种操作:

1.将一个数,从操作数序列的头端移到栈的头端(对应数据结构栈的 push 操作)

2.将一个数,从栈的头端移到输出序列的尾端(对应数据结构栈的 pop 操作)

你的程序将对给定的 n,计算并输出由操作数序列 1,2,…,n 经过操作可能得到的输出序列的总数。

很显然这是一道递推题,两种思路来做

1.如果能一眼看出来这是卡特兰数的话,直接用卡特兰数做就行了

#include <bits/stdc++.h>
using 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]

#include <bits/stdc++.h>
using 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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值