您的位置:首页 > 编程语言 > PHP开发

PAT 1093 CountPAT

2017-02-14 19:49 267 查看
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");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: