您的位置:首页 > 其它

1093. Count PAT's (25)

2017-07-27 21:00 267 查看
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 105characters 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的时候,判断A前面有多少P,A后面有多少T,相乘相加

如果直接暴力解决肯定超时,120ms 

可以先做一个处理,把位置i前面的P的个数求出来

位置i后面T的个数求出来

然后在遍历一次求总数

我第一次提交3个超时点。把字符串长度赋值给一个变量,不要每次都进行strlen(s)这个操作。浪费时间

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<stack>
using namespace std;
int main(){
char s[100001];
gets(s);
long long p[100001];
long long t[100001];
p[0]=s[0]=='P'?1:0;
int len=strlen(s);
for(int i=1;i<len;i++){
if(s[i]=='P'){
p[i]=p[i-1]+1;
}
else p[i]=p[i-1];
}
t[len-1]=s[len-1]=='T'?1:0;
for(int i=len-2;i>=0;i--){
if(s[i]=='T'){
t[i]=t[i+1]+1;
}
else t[i]=t[i+1];
}
long long sum=0;
for(int i=0;i<len;i++){
if(s[i]=='A'){
//cout<<i<<" "<<p[i]<<" "<<t[i]<<endl;
sum=(sum%1000000007+(p[i]*t[i])%1000000007)%1000000007;
}
}
cout<<sum%1000000007;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: