题目:
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.
- 题目思路:“PAT”的数量即为每个"A"左边的“P”个数与右边的“T”个数的乘积之和。
- 易错点:取模应在每次累加时进行而非最后进行一次取模 ,否则会溢出。
题解:
#include <stdio.h>
#include <iostream>
#include <cstring>
const int MAX_N=100010;
const int MOD=1000000007;
int main(){
char str[MAX_N];
scanf("%s",str);
int len = strlen(str);
int P[len],T[len];//P记录该下标左边P的个数,T记录该下标右边T的个数
int ans=0;
int num_p=0,num_t=0;
for(int i=0;i<len;i++){
if(str[i]=='P') num_p++;//这个字母不加,后面的才加(这个顺序不会对结果造成影响)
P[i]=num_p;
if(str[len-i-1]=='T') num_t++;
T[len-i-1]=num_t;
}
for(int j=0;j<len;j++){
if(str[j]=='A')
ans = (ans + P[j]*T[j])%MOD;//累计乘积时就应取模,否则int可能装不下
}
printf("%d\n",ans);
return 0;
}