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前面有cnt_p个P,就有p个PA组合,后面有t个T,就有t个AT组合,那么一共就会有p * t 个PAT组合,只需要遍历一次,用cnt_t来计数T的个数,cnt_p来计数P的个数,遇到一个A就把当前的cnt_p、cnt_t的值及其A的下标保存起来,遍历完后,P和T的总数量为cnt_p、cnt_t respectively,每个A前的P数为当时保存的cnt_p的值,A后的T数为cnt_t - 当时保存的cnt_t的值,乘积做累加,对1000000007取模后便是结果。
#include<iostream>
#include<vector>
using namespace std;
struct node
{
int cnt_p;
int cnt_t;
int index_a;
};
int main(){
vector<node> vec;
string s;
cin >> s;
int cnt_p = 0;
int cnt_t = 0;
for(int i = 0; i < s.length(); i++){
if(s[i] == 'A'){
node temp;
temp.cnt_p = cnt_p;
temp.cnt_t = cnt_t;
temp.index_a = i;
vec.push_back(temp);
}
if(s[i] == 'T'){
cnt_t++;
}
if(s[i] == 'P'){
cnt_p++;
}
}
int cnt = 0;
for(int i = 0; i < vec.size(); i++){
cnt += vec[i].cnt_p * (cnt_t - vec[i].cnt_t);
cnt = cnt % 1000000007;
}
cout << cnt << endl;
return 0;
}