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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章