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(n3)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");
}

189

被折叠的 条评论
为什么被折叠?



