【c++】PAT甲级1093/乙级1040 Count PAT's (25/25分)

  1. 题目

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

  1. 代码
#include
#include
using namespace std;
const int maxn=100010;
const int mod=1000000007;
int main(){
	char inp[maxn];
	int P[maxn]={0};
	//gets(inp); 编译错误 
	scanf("%s",inp);
	int len,out=0,T=0;
	len=strlen(inp);
	for(int i=0;i<len;i++){
		if (inp[i]=='P'){
			if (i==0) P[i]=1;
			else P[i]=P[i-1]+1;
		}else{
			if (i!=0) P[i]=P[i-1];
		}
	}
	for (int i=len-1;i>=0;i--){
		if (inp[i]=='T'){
			T++;
		}else if (inp[i]=='A'){
			out+=P[i]*T%mod;
			out%=mod;
		}
	}
	printf("%d",out);
	return 0;
} 
  1. 泪点

如果用暴力搜索会超时,且gets()在c++(g++)中会编译错误。

基本思想:若固定一个A,则PAT的数量=A左边P的数量*A右边T的数量。

PS:记得取余。

你可能感兴趣的:(PAT,c++)