Author: CAO, Peng
Organization: Google
Time Limit: 150 ms
Memory Limit: 64 MB
Code Size Limit: 16 KB
B1040/A1093. Count PAT’s (25)
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
Code
//NKW 乙级真题1030
#include <stdlib.h>
#include <iostream>
#include <string>
#define MAXN 1000000007
using namespace std;
string s;
int main(){
long long cnt = 0, c1 = 0, c2 = 0;
cin >> s;
for (int i = 0; i < s.length(); i++)
if (s[i] == 'T') c2++; // 首先统计所有T的个数
for (int i = 0; i < s.length(); i++){
if (s[i] == 'P') c1++; // 统计某个A前P的个数
else if (s[i] == 'T') c2--; // 统计某个A后T的个数
else cnt = (cnt + (c1*c2) % MAXN) % MAXN;
}
cout << cnt << endl;
return 0;
}
Analysis
-经过前三天,前三节(贪心、二分、two pointers)的摧残,终于做到一道水题。感动的快哭了。
-这道题一开始我第二个循环写成:(错在最后结果没有取模,啊啊啊啊好傻的错误(2020.1.30))
for (int i = 0; i < s.length(); i++){
if (s[i] == 'P') c1++;
else if (s[i] == 'T') c2--;
else cnt += (c1*c2) % MAXN;
}
-在PTA上好心的过了我2个测试点,而NKW上全部没通过,这让我体会到了PAT出测试点的人的用心以及好心。。。
-对于有几个PAT,只需找到字符串中的A,然后把这个A之前的P的个数*这个A之后的T的个数即可。