Codeforces Global Round 7 比赛人数10630
[codeforces 1326D1] Prefix-Suffix Palindrome (Easy version) 首尾回文+自左往右最大回文+自右往左最大回文
总目录详见https://blog.csdn.net/mrcrack/article/details/103564004
也在线测评地址https://codeforces.ml/contest/1326/problem/D1
Problem | Lang | Verdict | Time | Memory |
---|---|---|---|---|
D1 - Prefix-Suffix Palindrome (Easy version) | GNU C++11 | Accepted | 31 ms | 0 KB |
手工算法如下
acbba
acbba首尾回文a a,剩下字串cbb
cbb自左往右最大回文b
cbb自右往左最大回文bb
自左往右最大回文,自右往左最大回文,取最大回文bb
输出为abba
AC代码如下,因为比赛时追求的是成功率,故编得有些冗长。读者根据上面的思路,应能编得更简洁
#include <stdio.h>
#include <string.h>
#define maxn 5010
char s[maxn],a[maxn],b[maxn];
int main(){
int t,i,len,j,l,r,flag,tag,m,n;
scanf("%d",&t);
while(t--){
scanf("%s",s);
len=strlen(s),flag=0;
for(i=0;i<len/2;i++)
if(s[i]==s[len-1-i]) a[i]=s[i];
else{ flag=1;break;}
if(flag){
l=i,r=len-1-i;
//printf("l=%d r=%d\n",l,r);
a[i]='\0',len=i;
for(i=0;i<len;i++)b[i]=a[len-1-i];
b[i]='\0';
//printf("a=%s b=%s\n",a,b);
for(i=l;i<=r;i++){//自左向右找
if(s[l]==s[i]){
len=i-l+1,tag=0;
for(j=0;j<len/2;j++)
if(s[l+j]==s[l+len-1-j])continue;
else {tag=1;break;}
if(tag==0)m=i;
}
}
for(i=l;i<=r;i++){//自右向左找
if(s[i]==s[r]){
//printf("i=%d r=%d\n",i,r);
len=r-i+1;tag=0;
for(j=0;j<len/2;j++)
if(s[i+j]==s[i+len-1-j])continue;
else{tag=1;break;}
if(tag==0){n=i;break;}
}
}
//printf("l=%d m=%d n=%d r=%d\n",l,m,n,r);
if(m-l>r-n){//取左
len=strlen(a);
for(i=l;i<=m;i++)a[len+i-l]=s[i];
a[len+m-l+1]='\0';
strcat(a,b);
printf("%s\n",a);
}else{//取右
len=strlen(a);
for(i=n;i<=r;i++)a[len+i-n]=s[i];
a[len+r-n+1]='\0';
strcat(a,b);
printf("%s\n",a);
}
}else{
printf("%s\n",s);
}
}
return 0;
}