PAT 1093 CountPAT

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(不要求连续)

思路:

以字符A的每个位置为循环变量,查看每一个A之前有多少个P,以及之后有多少个T,乘之,累加

坑:

1.超时:不能三段遍历,会超时,采用数组记录计数量的办法,一次遍历下来,可知道在每个位置之前P和T字符的数量,分别保存在P_count和T_count数组之中,最后一次遍历即可得出结果

2.可能数字会非常大,应采用long long int变量保存


Code:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>
#include <stdio.h>


#define MAXN 100000


int main() {
std::vector<int> A_pos;
int P_count[MAXN], T_count[MAXN];
std::string input;
std::cin >> input;
P_count[0] = input[0] == 'P' ? 1 : 0;
T_count[0] = input[0] == 'T' ? 1 : 0;
for (int i = 1; i < input.size(); i++) {
P_count[i] = P_count[i - 1];
T_count[i] = T_count[i - 1];
if (input[i] == 'P') {
P_count[i]++;
}
if (input[i] == 'T') {
T_count[i]++;
}
if (input[i] == 'A') {
A_pos.push_back(i);
}
}
int total_T = T_count[input.size()-1];
// printf("total_t is %d\n", total_T);
long long int total_num = 0;
for (int i = 0; i < A_pos.size(); i++) {
int a_pos = A_pos[i];
total_num += P_count[a_pos-1] * (total_T-T_count[a_pos]);
// printf("a_pos is %d, p_count is %d, t_count is %d\n", a_pos, P_count[a_pos], T_count[a_pos]);
}
printf("%d", total_num % 1000000007);
system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值