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 10e5
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
Note
- 题意: 找有几个不同的pat,只要有一个字母不同就算
- 思路: 找到a的位置,前面有n个p 后面有m个t则此a产生m*n个pat。
- 一开始利用两层循环嵌套,先循环找到a,再循环往前往后找p和t,时间复杂度依旧为O(n ^ 2),正确思路应该是遍历两边
- 注意mod的时候, 不能写成 sum+= xxxx % xxx 了
- 段错误一般为溢出
- 书 p149
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
const int maxn = 1e7;
int tempp[maxn]={0}, tempt[maxn] = {0};
int main(){
int sum = 0;
string s;
cin >> s;
tempp[0] = (s[0] == 'P')? 1 : 0;
for(int i = 1; i < s.size(); i++){
tempp[i] = tempp[i - 1];
if(s[i] == 'P') tempp[i]++;
}
int len = s.size();
tempt[len - 1] = (s[len - 1] == 'T')? 1 : 0;
for(int i = s.size() - 2; i >= 0; i--){
tempt[i] = tempt[i + 1];
if(s[i] == 'T') tempt[i]++;
else if(s[i] == 'A') sum = (sum + tempp[i] * tempt[i] )% 1000000007;
}
cout << sum;
return 0;
}