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
思路(参照算法笔记):每个以A为中心的"PAT"的个数都等于这个A,左边P的个数*右边T的个数,所以只需要用数组记录并统计P和T的个数就好了。
第一次代码:(错在T的个数应该从右往左数)
#include<bits/stdc++.h>
using namespace std;
int yu=1000000007;
int main(){
char s[100005];
scanf("%s",s);
int P_count[100005]={0},T_count[10005]={0},ans=0;
for(int i=0;i<strlen(s);i++){
if(i==0){
if(s[i]=='P')P_count[0]=1;
else if(s[i]=='T')T_count[0]=1;
continue;
}
if(s[i]=='P')
P_count[i]=P_count[i-1]+1;
else
P_count[i]=P_count[i-1];
if(s[i]=='T')
T_count[i]=P_count[i-1]+1;
else
T_count[i]=T_count[i-1];
if(s[i]=='A')
ans+=(P_count[i]%yu)*(T_count[i]%yu);
}
printf("%d",ans);
return 0;
}
第二次代码(部分正确,2对3超时,为什么会超时呢?):
#include<bits/stdc++.h>
using namespace std;
int yu=1000000007;
int main(){
char s[100005];
scanf("%s",s);
int P_count[100005]={0},T_count=0,ans=0;
for(int i=0;i<strlen(s);i++){
if(i==0&&s[i]=='P'){
P_count[i]=1;
continue;
}
if(s[i]=='P')
P_count[i]=P_count[i-1]+1;
else
P_count[i]=P_count[i-1];
}
for(int i=strlen(s)-1;i>=0;i--){
if(s[i]=='T')
T_count++;
else if(s[i]=='A'){
ans+=(P_count[i]*T_count)%yu;
}
}
printf("%d",ans);
return 0;
}
如果事先将int len=strlen(s),则不会超时!教训!不过还是会有两个错误。
这两个错误是因为,必须每次更新ans都取余!
AC代码:
#include<bits/stdc++.h>
using namespace std;
int yu=1000000007;
int main(){
char s[100005];
scanf("%s",s);
int P_count[100005]={0},T_count=0,ans=0,len=strlen(s);
for(int i=0;i<len;i++){
if(i==0&&s[i]=='P'){
P_count[i]=1;
continue;
}
if(s[i]=='P')
P_count[i]=P_count[i-1]+1;
else
P_count[i]=P_count[i-1];
}
for(int i=len-1;i>=0;i--){
if(s[i]=='T')
T_count++;
else if(s[i]=='A'){
ans=(ans+P_count[i]*T_count)%yu;
}
}
printf("%d",ans);
return 0;
}
ans=(ans+P_count[i]*T_count)%yu;