1.題目
“答案正确”是自動判題系統給出的最令人歡喜的回複。本題屬于 PAT 的“答案正确”大派送 —— 隻要讀入的字元串滿足下列條件,系統就輸出“答案正确”,否則輸出“答案錯誤”。
得到“答案正确”的條件是:
- 字元串中必須僅有
、P
、A
這三種字元,不可以包含其它字元;T
- 任意形如
的字元串都可以獲得“答案正确”,其中xPATx
或者是空字元串,或者是僅由字母x
組成的字元串;A
- 如果
是正确的,那麼aPbTc
也是正确的,其中aPbATca
、a
、b
均或者是空字元串,或者是僅由字母c
組成的字元串。A
現在就請你為 PAT 寫一個自動裁判程式,判定哪些字元串是可以獲得“答案正确”的。
輸入格式:
每個測試輸入包含 1 個測試用例。第 1 行給出一個正整數 n (<10),是需要檢測的字元串個數。接下來每個字元串占一行,字元串長度不超過 100,且不包含空格。
輸出格式:
每個字元串的檢測結果占一行,如果該字元串可以獲得“答案正确”,則輸出
YES
,否則輸出
NO
。
輸入樣例:
8
PAT
PAAT
AAPATAA
AAPAATAAAA
xPATx
PT
Whatever
APAAATAA
輸出樣例:
YES
YES
YES
YES
NO
NO
NO
NO
2.題目分析
1.開始按照題目要求完成了輸入樣例的輸出,結果全錯…………
經過查閱了解題目中蘊含的規律(參見https://www.cnblogs.com/Anber82/p/11112682.html)
規律1:字元串中隻能有一個P,一個T,若幹(大于0)個A
規律2:字元串中不可以有除P、A、T之外别的字元
規律3:P前面A的個數為a,P到T之間的A的個數為b,T後A的個數為c,若a*b==c即符合要求(不服不行……)
3.代碼
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
bool d = false;
string temp;
cin >> temp;
int a = 0, b = 0, c = 0;
if (count(temp.begin(), temp.end(), 'P')>1 || count(temp.begin(), temp.end(), 'T')>1) { cout << "NO" << endl; continue; }
if(count(temp.begin(), temp.end(), 'P')<1|| count(temp.begin(), temp.end(), 'A')<1|| count(temp.begin(), temp.end(), 'T')<1) { cout << "NO" << endl; continue; }
for (int j = 0; j < temp.length(); j++)
if (temp[j] != 'P'&&temp[j] != 'A'&&temp[j] != 'T') { cout << "NO" << endl; d = true; break; }
if (d == true)continue;
a = temp.find('P');
c = temp.length()-1-temp.find('T');
b = temp.find('T') - temp.find('P') - 1;
if (a*b == c)cout << "YES" << endl;
else cout << "NO" << endl;
}
}