1093 Count PAT's(DP)

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数量,条件:只要满足P、A、T这个顺序即可,可不连续,也可重复使用字母。
可用DP的思想,遍历字符串,当遍历到P时,更新P的数量p;当遍历到A时,将PA组合的数量a加上该A前面P的数量,即a = a + p;同理当遍历到T时,cnt = cnt + a。

AC代码

#include <iostream>
#include <string> 
using namespace std; 

int main(){ 		
	int p = 0, a = 0; //p代表p的个数 a代表pa组合的个数
	long long cnt = 0; //pat的个数
	string str;
	cin>>str;
	for(int i = 0; i < str.size(); i++){
		if(str[i] == 'P')
			p++;
		else if(str[i] == 'A')
			a += p;
		else if(str[i] == 'T')
			cnt += a;
	} 
	cnt %= 1000000007;
	cout<<cnt;
	return 0;
}
发布了110 篇原创文章 · 获赞 0 · 访问量 1260

猜你喜欢

转载自blog.csdn.net/qq_43072010/article/details/105467369