1003. 我要通过!(20)

来源:互联网 发布:网络流最短路径增值 编辑:程序博客网 时间:2024/04/29 01:31

1003. 我要通过!(20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”。

得到“答案正确”的条件是:

1. 字符串中必须仅有P, A, T这三种字符,不可以包含其它字符;
2. 任意形如 xPATx 的字符串都可以获得“答案正确”,其中 x 或者是空字符串,或者是仅由字母 A 组成的字符串;
3. 如果 aPbTc 是正确的,那么 aPbATca 也是正确的,其中 a, b, c 均或者是空字符串,或者是仅由字母 A 组成的字符串。

现在就请你为PAT写一个自动裁判程序,判定哪些字符串是可以获得“答案正确”的。

输入格式: 每个测试输入包含1个测试用例。第1行给出一个自然数n (<10),是需要检测的字符串个数。接下来每个字符串占一行,字符串长度不超过100,且不包含空格。

输出格式:每个字符串的检测结果占一行,如果该字符串可以获得“答案正确”,则输出YES,否则输出NO。

输入样例:
8PATPAATAAPATAAAAPAATAAAAxPATxPTWhateverAPAAATAA
输出样例:
YESYESYESYESNONONONO

提交代码

优化前:

#include<stdio.h>
#include<string.h>
int main()
{
int c,len,q,i,j=0,countp,counta,countt,k,count1,count2,count3,m,n,coun;
char s[101];
scanf("%d",&c);
for(q=0;q<c;q++)
{
countp=0;
counta=0;
countt=0;
coun=0;
k=0;
j=0;
count1=0;
count2=0;
count3=0;
scanf("%s",s);
        //  gets(s);
len=strlen(s);


while(s[j]!='\0')
{
if(s[j]=='P')
{
countp++;
}
else if(s[j]=='A')
{
counta++;
}
 else if(s[j]=='T')
{
countt++;
}else
{
printf("NO\n");
coun++;
break;
// return 0;
 //  continue;
}
j++;
}
//保证PT出现一次A至少一次,无其他 ,然后验证其规律 
if(countp==1&&countt==1&&counta!=0&&coun==0)
{
while(s[k]!='\0')
         {
        if(s[k++]=='P')
      {
      m=k-1;
    }
    }
  k=0;
    while(s[k]!='\0')
       {
        if(s[k++]=='T')
      {
      n=k-1;
    }
       
  }
for(i=0;i<m;i++)
   {
   if(s[i]=='A')
   {
   count1++;
}
   
 }
  for(i=n+1;i<len;i++)
   {
   if(s[i]=='A')
   {
   count3++;
}
 }
 for(i=m+1;i<n;i++)
 {
  if(s[i]=='A')
  {
  count2++;
}
 }
  if(count1*count2==count3)
  {
printf("YES\n");
}else{
printf("NO\n");
}
}else
{
if(coun!=0)
{
continue;


}
printf("NO\n");
}

}
}


优化后:#include<stdio.h>
#include<string.h>
int main(){
    int n,i,j;
    int cntp=0,cntt=0;
    char s[101];
    char *p1,*p2;
    scanf("%d",&n);
    for(i=0;i<n;++i){
        scanf("%s",&s);
        int cntp=0,cntt=0,cnta=0,ispat=0;
        /* 对s进行遍历,记录PAT三个字母出现的次数,
        若出现其他字符直接结束测试 */ 
        for(j=0;s[j]!='\0';++j){
            if(s[j]=='P') ++cntp;
            else if(s[j]=='T') ++cntt;
            else if(s[j]=='A') ++cnta;
            else goto endtest;
        }
        /* 当P和T都只有1个,A至少1个时,
        计算是否符合规律 */ 


        if(cntp==1&&cntt==1&&cnta!=0){
            p1=strchr(s,'P');
            p2=strchr(s,'T');
            if((p1-s)*(p2-p1-1)==strlen(p2)-1){
                ispat=1;
            }
        }
        endtest:
        if(ispat) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

0 0