1093 Count PAT's (25 point(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 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
思路:遍历输入的串,如果是A,用A前面的P的数量乘以A后面的T的数量就是当前这个A可以构造的PAT的数量。为了快速得到A后面的T的数量,先遍历一遍字符串, 计算字符串中所有T的数量。这样总共需要遍历两次字符串。
#include <string>
#include <iostream>
using namespace std;
const int maxn = 100005;
int main()
{
string in;
getline(cin, in);
int allT = 0;//所有T的数量
int preT = 0;//已经遍历到的T的数量
int preP = 0;//已经遍历到的P的数量
long long PAT = 0;//PAT的数量
for(int i = 0; i < in.size(); i++)
if(in[i] == 'T')
allT++;
for(int i = 0; i < in.size() - 1; i++)
{
if(in[i] == 'P')
preP++;
else if(in[i] == 'T')
preT++;
else //is 'A'
{
PAT += preP * (allT - preT);
if(PAT >= 1000000007)
PAT %= 1000000007;
}
}
cout << PAT;
return 0;
}