PAT 甲级 1093 Count PAT’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
思路
刚开始使用暴力求解,结果6个测试用例超时了4个。后来想了一下,可以改变存储结构来改变运行时间。此题换一个角度想想,其实是可以以A
的位置作为中轴,那么以这个A
作为中轴的PAT
个数有多少呢?其实就是这个位置之前的P
的个数和这个位置之后的T
的个数的乘积。换成这样一想,原本
O
(
n
3
)
O(n^3)
O(n3)的暴力求解复杂度一下子降到了
O
(
n
)
O(n)
O(n),即用三个vector
存储,俩个存储各个位置以前的P
的个数和T
的个数,一个用来存储A
的位置。然后用一遍扫描存储A
位置的数组,用乘法就可以做出答案。别忘了最后mod 1000000007 。
AC代码
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <set>
using namespace std;
vector<int> countP, countT, posA;
int main() {
string s;
cin >> s;
long long count = 0;
if (s[0] == 'P') {
countP.push_back(1);
countT.push_back(0);
}
else if (s[0] == 'T') {
countT.push_back(1);
countP.push_back(0);
}
else {
posA.push_back(0);
countT.push_back(0);
countP.push_back(0);
}
for (int i = 1; i < s.length(); i++) {
if (s[i] == 'P') {
countP.push_back(countP[i - 1] + 1);
countT.push_back(countT[i - 1]);
}
else if (s[i] == 'T') {
countT.push_back(countT[i - 1] + 1);
countP.push_back(countP[i - 1]);
}
else {
posA.push_back(i);
countT.push_back(countT[i - 1]);
countP.push_back(countP[i - 1]);
}
}
for (int i = 0; i < posA.size(); i++) {
count += ((long long)countP[posA[i]] * (long long)(countT[s.length() - 1] - countT[posA[i]]));
if (count >= 1000000007) {
count = count % 1000000007;
}
}
cout << count;
system("pause");
}