PAT A1093 Count PAT's 有几个PAT【递推】

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.

字符串APPAPT包含了两个PAT。第一个是由 第二个、第四个、第六个字符组成的,第二个是由第三个第四个第六个字符组成的。

现在给你任意字符串,你需要说出里面包含了几个PAT

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 PA, or T.

每一个测试样例只有一行,给出了一个不超过10^5个字符组成的字符串。只包含P、A、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.

对于每一个测试样例,用一行打印出字符串里包含的PAT的个数,如果结果是一个很大的数字,你只需要输出结果%1000000007

#include<cstdio>
#include<cstring>
const int MAXN=100010;
const int MOD=1000000007;
char str[MAXN];
int leftNumP[MAXN]={0};

int main(){
	scanf("%s",str);
	int len=strlen(str);
	for(int i=0;i<len;i++){
		if(i>0){
			leftNumP[i]=leftNumP[i-1];//继承上一位的结果 
		}
		if(str[i]=='P') leftNumP[i]++;
	}
	int ans=0,rightNumT=0;
	for(int i=len-1;i>=0;i--){
		if(str[i]=='T') rightNumT++;
		else if(str[i]=='A') ans=(ans+leftNumP[i]*rightNumT)%MOD;
	}
	printf("%d\n",ans);
	return 0;
}

思路:对一个确定位置的A来说,以它形成的PAT的个数等于它左边P的个数乘以它右边T的个数。于是问题转换为:对字符串中的每个A,计算它左边P的个数与它右边T的个数的乘积,然后把所有A的这个乘积相加。

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/86669137