1093. Count PAT's (25)

来源:互联网 发布:nemo软件好用吗 编辑:程序博客网 时间:2024/05/31 18:30

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;}