【PAT甲级 - C++题解】1093 Count PAT‘s

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1093 Count PAT’s (pintia.cn)
🔑中文翻译:PAT 计数
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

1093 Count PAT’s

The string APPAPT contains two PAT’s as substrings. The first one is formed by the 2nd, the 4th, and the 6th characters, and the second one is formed by the 3rd, the 4th, and the 6th characters.

Now given any string, you are supposed to tell the number of PAT’s contained in the string.

Input Specification:

Each input file contains one test case. For each case, there is only one line giving a string of no more than 105 characters containing only P, A, or T.

Output Specification:

For each test case, print in one line the number of PAT’s contained in the string. Since the result may be a huge number, you only have to output the result moded by 1000000007.

Sample Input:

APPAPT

Sample Output:

2
题意

给定一个字符串,请你求出字符串中包含的 PAT 的数量。

思路

这道题可以用动态规划状态机来做,将需要匹配的字符串 PAT 转换成状态,为了方便计算,我们将空格设置为初始状态 0 ,然后在从前往后遍历字符串 s 的时候就计算一遍所有的状态,每个状态都是由它前一个状态转移过来。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RxhmqWj0-1667989071807)(PAT 甲级辅导.assets/22.png)]

状态表示: f [ i ] [ j ] f[i][j] f[i][j] 表示只考虑前 i 个字母且走到了状态 j 的所有路线的数量。

状态计算:

如果当前遍历的字符不属于 PAT 中的字符,则将上一轮对应状态的数量转移到这一轮中: f [ i ] [ j ] = f [ i − 1 ] [ j ] f[i][j]=f[i-1][j] f[i][j]=f[i1][j]

如果满足要求,则加上上一轮该状态的前一个状态的数量: f [ i ] [ j ] = ( f [ i ] [ j ] + f [ i − 1 ] [ j − 1 ] ) % M O D f[i][j]=(f[i][j]+f[i-1][j-1])\%MOD f[i][j]=(f[i][j]+f[i1][j1])%MOD

代码
#include<bits/stdc++.h>
using namespace std;

const int N = 100010, MOD = 1000000007;
char s[N], p[] = " PAT";
int f[N][4];

int main()
{
    cin >> s + 1;
    int n = strlen(s + 1);

    f[0][0] = 1;  //初始化
    for (int i = 1; i <= n; i++)   //遍历每个字符
        for (int j = 0; j < 4; j++)    //遍历每个状态
        {
            f[i][j] = f[i - 1][j];  //将上一轮的状态转移过来
            //如果满足条件,则更新数量
            if (s[i] == p[j])  f[i][j] = (f[i][j] + f[i - 1][j - 1]) % MOD;
        }

    cout << f[n][3] << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值