【PAT】A1093 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 10^5characters 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”这个字符串只有3个字符,所以只需要对每一个“A”计数它左边的"P的个数"和右边的"T"的个数就可以了。遍历"T"字符的同时计算结果,可以少写一个循环结构。

代码

#include <cstdio>
#include <cstring>
#define MAX_N 100001
int main() {
    char str[MAX_N];
    int leftPCnt[MAX_N], len;
    scanf("%s", str);
    len = strlen(str);
    // 计数每一个字符及其左边的'P'的个数
    for(int i = 0, t = 0; i < len; i++){
        if(str[i] == 'P') t++;
        leftPCnt[i] = t;
    }
    
    // 从右往左遍历,累计当前字符右边的'T'的个数,同时计算结果
    long res = 0;
    for(int i = len - 1, t = 0; i >= 0; i--){
        if(str[i] == 'T'){
             t++;
        }else if(str[i] == 'A'){
            res += (leftPCnt[i] * t) % 1000000007;
        }
    }
    printf("%ld", res % 1000000007);
    return 0;
}

版权声明:本文为a617976080原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。