PTA甲级 Count PAT (25分)

@


首先,先贴柳神的博客

https://www.liuchuo.net/ 这是地址

想要刷好PTA,强烈推荐柳神的博客,和算法笔记

题目原文

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 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

思路如下:

这个思路,我是按照算法笔记的来写的.

对一个确定位置的A来说,以它形成的PAT的个数等于它左边P的个数乘以它右边T的个数

所以我们就要求,对于每一个确定的A,计算它左边的P的个数,和它右边的T的个数的乘积.

① 我们创建一个leftNum的数组,记录每一个左边的P的个数(包含当前位)--计算这个从左到右

② 在计算T的时候,我们从右到左,用一个rightNum的变量来保存,碰到T就加一.然后碰到A就直接计算,最后结果记得取模.

代码如下:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
const int MAXN = 100010;
const int MOD = 1000000007;
int main(void){
	string a;
	cin>>a;
	long long sum=0;
	vector<int> leftNum(a.size(),0);
	if(a[0] == 'P')	leftNum[0]=1;
	for(int i = 1;i < a.size();++i){
		if(a[i] == 'P'){
			leftNum[i]=leftNum[i-1]+1;
		}
		else{
			leftNum[i]=leftNum[i-1];
		}
	}
	long long  rightNumT=0;
	for(int i=a.size()-1;i>=0;i--){
		if(a[i]=='T'){
			++rightNumT;
		}
		else if(a[i] == 'A'){
			sum+=(leftNum[i]*rightNumT);
		}
	}
	sum = sum %MOD;
	cout<<sum<<endl;
	return 0;
}

下面是我(划去)柳神的代码

地址

思路:

先遍历字符串数一数有多少个T 然后每遇到一个T呢~countt–;每遇到一个P呢,countp++;然后一遇

到字母A呢就countt * countp 把这个结果累加到result中 最后输出结果就好啦 对了别忘记要

对10000000007取余哦~

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s;
    cin >> s;
    int len = s.length(), result = 0, countp = 0, countt = 0;
    for (int i = 0; i < len; i++) {
        if (s[i] == 'T')
            countt++;
    }
    for (int i = 0; i < len; i++) {
        if (s[i] == 'P') countp++;
        if (s[i] == 'T') countt--;
        if (s[i] == 'A') result = (result + (countp * countt) % 1000000007) % 1000000007;
    }
    cout << result;
    return 0;
}
posted @ 2020-06-25 16:09  黄鹏宇  阅读(285)  评论(0)    收藏  举报