1.題目
字元串
APPAPT
中包含了兩個單詞
PAT
,其中第一個
PAT
是第 2 位(
P
),第 4 位(
A
),第 6 位(
T
);第二個
PAT
是第 3 位(
P
),第 4 位(
A
),第 6 位(
T
)。
現給定字元串,問一共可以形成多少個
PAT
?
輸入格式:
輸入隻有一行,包含一個字元串,長度不超過105,隻包含
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;
}