PAT (Advanced Level) Practice 1093 Count PAT‘s (25 分)

topic

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 1 0 5 {10^5} 105​​ 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

method
① Count the length of each input character, and then count the number of P accumulated at each position
② Count the cumulative number of T from the end to the head, and look for A
③ Whenever A is found, the accumulated P at the current position Multiply the number by the cumulative number of T

Code

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e7;
int main()
{
    
    
	string s;
	cin >> s;
	int sum = 0;
	
	int np[s.length()];
	int nt[s.length()];
	
	if(s[0] == 'P')
		np[0] = 1;
	else 
		np[0] = 0;
		
	for(int i = 1;i < s.length();i++)
	{
    
    
		if(s[i] == 'P')
			np[i] = np[i-1] + 1;
		else
			np[i] = np[i-1];
	}
	
	if(s[s.length()-1] == 'T')
		nt[s.length()-1] = 1;
	else 
		nt[s.length()-1] = 0;

	for(int i = s.length() - 2;i >= 0;i--)
	{
    
    
		nt[i] = nt[i+1];
		if(s[i] == 'A')
		{
    
    
			sum = (sum + np[i]*nt[i]) % 1000000007;
		}
		else if(s[i] == 'T')
		{
    
    
			nt[i] = nt[i+1] + 1;
		}
	}
	cout << sum;
}

Guess you like

Origin blog.csdn.net/weixin_43820008/article/details/114261399