原题如下:
“答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于 PAT 的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”。
得到“答案正确”的条件是:
- 字符串中必须仅有
P
、A
、T
这三种字符,不可以包含其它字符; - 任意形如
xPATx
的字符串都可以获得“答案正确”,其中x
或者是空字符串,或者是仅由字母A
组成的字符串; - 如果
aPbTc
是正确的,那么aPbATca
也是正确的,其中a
、b
、c
均或者是空字符串,或者是仅由字母A
组成的字符串。
现在就请你为 PAT 写一个自动裁判程序,判定哪些字符串是可以获得“答案正确”的。
输入样例:
10
PAT
PAAT
AAPATAA
AAPAATAAAA
xPATx
PT
Whatever
APAAATAA
APT
APATTAA
结尾无空行
输出样例:
YES
YES
YES
YES
NO
NO
NO
NO
NO
NO
结尾无空行
代码如下
#include <iostream>
#include <string>
using namespace std;
int jud(string);//judge
int main()
{
int N, n;
cin >> N;
cin.get();//accept "\n"
string* s = new string[N];
for (int i = 0; i < N; i++)
{
getline(cin, s[i]);
}
for (int i = 0; i < N; i++)
{
n = jud(s[i]);
if (n==0)
{
cout << "NO";
}
else
{
cout << "YES";
}
if (i!=N-1)
{
cout << endl;
}
}
return 0;
}
int jud(string s)//judge whether the string meet the conditions
{
int len = s.length();
if (len<3)
{
return 0;
}
//check whether the first condition is met
for (int i = 0; i < len;)
{
if (s[i] == 'P' || s[i] == 'A' || s[i] == 'T')
{
i++;
}
else
{
return 0;
}
}
//the second and third condition
string s1 = "", s2 = "", s3 = "";
for (int i = 0; i < len-2; i++)
{
if (s[i]=='P')
{
for (int j = 2; i+j < len; j++)//The number of A betwenn P and T is j-1
{
if (s[i+j]=='T')
{
for (int k = 1; k < j; k++)
{
if (s[i+k]!='A')
{
return 0;
}
}
for (int k = 0; k < i; k++)
{
s1 = s1 + s[k];
if (s[k]!='A')
{
return 0;
}
}
for (int k = i+j+1; k < len; k++)
{
s2 = s2 + s[k];
if (s[k]!='A')
{
return 0;
}
}
for (int k = 0; k < j-1; k++)
{
s3 = s3 + s1;
}
if (s2==s3)
{
return 1;
}
}
}
}
}
return 0;
}
提交结果如下