【PAT】(B)1040 有幾個PAT
阿新 • • 發佈:2019-01-31
『題目』
字串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
『思路』
開始的思路 找出第一個“P”和第一個“A”中間“P”的個數p_cnt ,第一個“A”和第一個“T”中間“A”的個數a_cnt,第一個“T”到最後“T”的個數 t_cnt ans = p_cnt * a_cnt * t_cnt,但是忽略了“PATPAT”這種存在重複的問題,如果多次判斷會存在超時的問題。
所以採用以下思路:
從字串最後開始遍歷,如果是“T”,記錄。如果是“A”,記錄”AT“的個數。如果是“P”,則記錄“PAT”的個數。
『第一次程式碼』
#include <iostream> #include <string> using namespace std; int main() { string s; cin>>s; int p_index,a_index,t_index,len = s.length(); int p_cnt = 0,a_cnt = 0, t_cnt = 0; if(s.find_first_of('P') != string::npos) { p_index = s.find_first_of('P'); cout<<p_index<<"= p_index\n"; if( s.find_first_of('A',p_index) != string::npos) { a_index = s.find_first_of('A',p_index); cout<<a_index<<"= a_index\n"; if(s.find_first_of('T',a_index) != string::npos) { t_index = s.find_first_of('T',a_index); cout<<t_index<<"= t_index\n"; for(int i = p_index; i < a_index; i++) if(s[i] == 'P') p_cnt++; cout<<"p_cnt = "<<p_cnt<<"\n"; for(int i = a_index; i < t_index; i++) if(s[i] == 'A') a_cnt++; cout<<"a_cnt = "<<a_cnt<<"\n"; for(int i = t_index; i < len; i++) if(s[i] == 'T') t_cnt++; cout<<"t_cnt = "<<t_cnt<<"\n"; } } } int ans = p_cnt * a_cnt * t_cnt; ans %= 1000000007; cout<<ans; return 0; }
『AC程式碼』
#include <iostream> #include <string> using namespace std; int main() { string s; cin>>s; int len = s.length(); int pat_cnt = 0,at_cnt = 0, t_cnt = 0; for(int i = len - 1; i >=0; i--){ if(s[i] == 'T')//如果是T,則記錄T的個數 t_cnt++; else if(s[i] == 'A') at_cnt = (at_cnt + t_cnt) % 1000000007;//如果是A,則計算AT的個數 else pat_cnt = (pat_cnt + at_cnt) % 1000000007;//如果是P,則計算PAT的個數 } cout<<pat_cnt; return 0; }