高效技巧-活用递推
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 10
5
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
思路:
直接暴力会超时。
另一个角度。对于一个确定位置的A来说,以它形成的PAT的个数等于它左边P的个数乘以它右边T的个数。例如字符串APPAPT的中间的A来说,它左边有两个P,右边有一个T,所以这个A能形成2个PAT。因此本问题就可以看作,对字符串中的每个A,计算它左边的P和它右边的A的个数的乘积,然后把所有A的这个乘积相加。
那如何更快获得每一个A左边P的个数呢?
只需要设定一个数组leftNumP,记录每一个左边P的个数(包括当前位)。接着从左到右遍历字符串,如果当前一位i是P,那么leftNumP[i]就等于leftNumP[i-1]+1;如果当前位i不是P,那leftNumP[i]就等于leftNumP[i-1]。以同样的方法计算出每一个A右边T的个数。
另外,在统计每一个A右边T的个数时直接计算答案ans。具体方法:定义一个变量rightNumT,记录当前累计右边T的个数。从右往左遍历,如果当前位i是T,那么令rightNumT加1;否则,如果当前位i为A,那么令ans加上leftNumP[i]与rightNumT[i]的乘积(注意取模)。
注意:
1.采用分别遍历P、A、T的方法会超时。
2.记得取模。
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 100010;
const int MOD = 1000000007;
char str[MAXN];
int leftNumP[MAXN] = {0};
int main(){
cin.getline(str,MAXN);
int len = strlen(str);
for(int i=0;i<len;i++){
if(i > 0)
leftNumP[i] = leftNumP[i-1];
if(str[i] == 'P')
leftNumP[i]++;
}
int ans = 0,rightNumT = 0;
for(int i=len-1;i>=0;i--){
if(str[i] == 'T')
rightNumT++;
else if(str[i] == 'A')
ans = (ans + leftNumP[i]*rightNumT) % MOD;
}
printf("%d\n",ans);
return 0;
}