PAT B1040 有幾個PAT (25 分)
阿新 • • 發佈:2019-02-12
統計 計數 如果 max sys i++ else clu ans
字符串 APPAPT
中包含了兩個單詞 PAT
,其中第一個 PAT
是第 2 位(P
),第 4 位(A
),第 6 位(T
);第二個 PAT
是第 3 位(P
),第 4 位(A
),第 6 位(T
)。
現給定字符串,問一共可以形成多少個 PAT
?
輸入格式:
輸入只有一行,包含一個字符串,長度不超過1,只包含 P
、A
、T
三種字母。
輸出格式:
在一行中輸出給定字符串中包含多少個 PAT
。由於結果可能比較大,只輸出對 1000000007 取余數的結果。
輸入樣例:
APPAPT
輸出樣例:
2
#include <stdio.h> #include <algorithm> #include<cstring> using namespace std; const int maxn = 100010, mod = 1000000007; char s[maxn]; int p[maxn] = { 0 }; int main() { int N,K,L=0; int count = 0; scanf("%s", &s); N = strlen(s); //printf("%d", N); for (int i = 0; i < N; i++) { if (i > 0) { p[i] = p[i - 1]; } if (s[i] == ‘P‘) { p[i]++; } } int ans = 0, numT = 0; for (int i = N - 1; i > 0; i--) { if (s[i] == ‘T‘) { numT++; } else if (s[i] == ‘A‘) { ans = (ans + p[i] * numT) % mod; //ans = ans % mod;} } printf("%d", ans); system("pause"); return 0; }
註意點:先統計每個位置上前面有多少個P,再從後往前遍歷,遇到T就計數,遇到A就計算。如果再從尾到頭遍歷T而不是邊遍歷邊計算,容易超時。
PAT B1040 有幾個PAT (25 分)