PAT 1093 Count PAT‘s (25分)

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

思路:如何统计PAT呢?常规暴力解法就是计算每个A前面的P和后面的T个数,相乘即可,遍历所有是A的字符。很显然每次找到A后,先从前往后统计P的个数,然后遇到当前A停止,然后往后统计T个数,所以是N^2复杂度。很显然超时,如何优化呢,我们可以通过前缀和来实现。这里我要统计下标为i时,前面的P个数和后面的T个数。

#include
using namespace std;

typedef long long ll;
const int maxn = 1e5+10;
char str[maxn];
int p[maxn];  //下标为i前面的P个数 
int t[maxn];

const ll mod = 1000000007;
int main()
{
	scanf("%s",str+1);
	
	int len = strlen(str+1);
	for(int i = 1;i <= len;++i)
	{
		p[i] += p[i-1];
		if(str[i] == 'P')  p[i]++;
	} 
	
	for(int i = len;i >= 1;--i)
	{
		t[i] += t[i+1];
		if(str[i] == 'T') t[i]++;
	}
	
	ll res = 0;
	for(int i = 1;i <= len;++i)
	{
		if(str[i] == 'A') res = (res+p[i]%mod*t[i])%mod;
	}
	cout << res << endl;
	return 0;
}

 

你可能感兴趣的:(pat甲级)