栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

YbtOJ 栈的问题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

YbtOJ 栈的问题

现在可以进行两种操作:

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

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

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

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

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

#include 
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 
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/718345.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号