题目:
答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于 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
思路:
- 先判断字符串中是不是只有"P",“T”,"A"这三中字符;
- 判断”P","T"的个是否只有一个。并且"A"的个数不少于一个;
- 将字符串分为三个部分,"P"之前为第一段,"P"到"T"为第二段,"T"之后为第三段。这三段出现的"A"的次数记为num_1,num_2,num_3,判断num_1*num_2是否等于num_3;
代码:
#include <bits/stdc++.h>
using namespace std;
bool judge(string s)
{
int position_p, position_t, position_a;
int count_p = 0, count_t = 0, count_a = 0;
int num_1 = 0, num_2 = 0, num_3 = 0;
for (int i = 0; i < s.size(); i++)
{
if (s[i] != 'A' && s[i] != 'P' && s[i] != 'T')
return false;
if (s[i] == 'P')
count_p++;
if (s[i] == 'A')
count_a++;
if (s[i] == 'T')
count_t++;
}
if (count_p != 1 || count_a < 1 || count_t != 1)
return false;
position_a = s.find('A');
position_p = s.find('P');
position_t = s.find('T');
for (int i = 0; i < position_p; i++)
num_1++;
for (int i = position_p + 1; i < position_t; i++)
num_2++;
for (int i = position_t + 1; i < s.size(); i++)
num_3++;
if (num_1 * num_2 == num_3)
return true;
else
return false;
}
int main()
{
int n;
cin >> n;
string s;
for (int i = 0; i < n; i++)
{
cin >> s;
if (judge(s))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}