1. 程式人生 > >PAT1093: Count PAT's (25)

PAT1093: Count PAT's (25)

mit spa 測試 pan tro str cat 用兩個 limit

1093. Count PAT‘s (25)

時間限制 120 ms 內存限制 65536 kB 代碼長度限制 16000 B 判題程序 Standard 作者 CAO, Peng

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

思路

試了下直接暴搜,果然最後幾個測試點超時,看來還是得用dp。
這道題DP的思路就是用兩個int數組P[n],T[n]保存第i個字符的左邊字母‘P‘的個數P[i]和右邊字母‘T‘的個數T[i],當遍歷到的字符是‘A‘時,那麽以這個A為基礎的"PAT"字符串個數就是它左側P字母個數乘以右側T字母個數。即P[i]*T[i]

代碼
#include<iostream>
#include<vector>
using namespace std;
int main()
{
    string s;
    
while(cin >> s) { vector<int> P(100000,0); vector<int> T(100000,0); for(int i = 1,j = s.size() - 2;i < s.size() && j >= 0;i++,j--) { if(s[i - 1] == P) { P[i]++; } if(s[j + 1] == T) { T[j]++; } P[i] += P[i - 1]; T[j] += T[j + 1]; } int sum = 0; for(int i = 0;i < s.size();i++) { if(s[i] == A) { sum += P[i] * T[i]; sum %= 1000000007; } } cout << sum << endl; } }

PAT1093: Count PAT's (25)