天天看点

PAT (Basic Level) Practice 1040 有几个PAT (25分) 数学规律1.题目2.题目分析3.代码

1.题目

字符串 

APPAPT

 中包含了两个单词 

PAT

,其中第一个 

PAT

 是第 2 位(

P

),第 4 位(

A

),第 6 位(

T

);第二个 

PAT

 是第 3 位(

P

),第 4 位(

A

),第 6 位(

T

)。

现给定字符串,问一共可以形成多少个 

PAT

输入格式:

输入只有一行,包含一个字符串,长度不超过10​5​​,只包含 

P

A

T

 三种字母。

输出格式:

在一行中输出给定字符串中包含多少个 

PAT

。由于结果可能比较大,只输出对 1000000007 取余数的结果。

输入样例:

APPAPT
           

输出样例:

2
           

2.题目分析

PAT中使用A组成的个数:A前面的P的个数*A后面的T的个数

3.代码

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
	string temp;
	cin >> temp;
	long long int total = 0;
	for (int i = 0; i < temp.length(); i++)
		if (temp[i] == 'T')total++;

	long long int pcount = 0, tcount = 0, count = 0;
	for (int i = 0; i < temp.length(); i++)
	{
		if (temp[i] == 'P')pcount++;
		else if (temp[i] == 'T')tcount++;
		else count = count + pcount*(total-tcount);
	}
	cout << count % 1000000007;
	

}
           

 大神代码:(直接取余,无需long long https://www.liuchuo.net/archives/573)

#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;
}