问题描述:
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^5
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
思路还是比较简单的,输入的时候记录"当前已经遇到的P的个数",然后对遇到的A更新在它之前的P的个数。
同理,反向记录"当前已经遇到的T的个数",遇到A时可以得出当前的A可以组成多少个PAT。
#include <bits/stdc++.h>
using namespace std;
struct PAT {
char value;
int P;
};
PAT pat[100005];
int main() {
int Pn, Tn;
Pn = Tn = 0;
int len = 0;
long long ans = 0;
//从左到右算一次
while((pat[len].value = getchar()) != '\n') {
if (pat[len].value == 'P') Pn++;
else if(pat[len].value == 'A') pat[len].P = Pn;
len++;
}
//从右到左算一次
for (int i = len - 1; i >= 0; i--) {
if (pat[i].value == 'T') Tn++;
else if(pat[i].value == 'A') ans += Tn * pat[i].P;
}
printf("%lld", ans % 1000000007);
return 0;
}