zoj3816,Generalized Palindromic Number
又怒坑队友。
住兽医院住久了脑子都不好使了。
只需要枚举哪几位不变,再枚举一个数字作为对称轴就可以暴搞了。
没有回文串长为偶数的情况。这种可以被枚举哪个数字多填包含掉,这样就只要处理奇回文的情况了。
看代码吧,不懂请提问。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long n,ans;
int ts[25],ns[25],s[25];
int l;
void init(){
long long tn=n;
l=0;
int i;
while(tn){
ts[++l]=tn%10;
tn/=10;
}
for(i=1;i<=l;++i){
s[i]=ts[l+1-i];
}
}
void work(int now,int num){
int i,j,k;
int p,tlen,rl,ll,lp,rp,flag;
long long tv,tmp;
for(i=1;i<now;++i){
ts[i]=s[i];
}
ts[now]=num;
p=0;
ns[++p]=ts[1];
for(i=2;i<=now;++i){
if (ts[i]!=ts[i-1]) ns[++p]=ts[i];
}
tv=0;
for(i=1;i<=now;++i){
tv=tv*10+ts[i];
}
if (l-now>=p){
tlen=l-now-p;
tmp=tv;
for(i=1;i<=tlen;++i){
tmp=tmp*10+9;
}
for(i=p;i>=1;--i){
tmp=tmp*10+ns[i];
}
if (tmp>ans) ans=tmp;
}
for(i=p;i>=1;--i){
lp=i-1;rp=i+1;
flag=1;
for(;lp>=1&&rp<=p;--lp,++rp){
if (ns[lp]!=ns[rp]) {flag=0;break;}
}
if (flag==1){
if (lp==0){
for(;rp<=p;++rp){
if (ns[1]!=ns[rp]) {flag=0;break;}
}
if (flag==0) continue;
tmp=tv;
for(j=now+1;j<=l;++j){
tmp=tmp*10+ns[1];
}
if (tmp>ans) ans=tmp;
}
else{
rl=l-now;ll=lp;
tlen=rl-ll;
if (tlen<0) {flag=0;continue;}
for(j=lp+1;j>=1;--j){
tmp=tv;
for(k=lp;k>j;--k){
tmp=tmp*10+ns[k];
}
for(k=1;k<=tlen;++k){
tmp=tmp*10+ns[j];
}
for(k=min(lp,j);k>=1;--k){
tmp=tmp*10+ns[k];
}
if (tmp>ans) ans=tmp;
}
}
}
}
}
int cas,i,j;
int main(){
//freopen("hin.txt","r",stdin);
scanf("%d",&cas);
while(cas--){
scanf("%lld",&n);
init();
ans=-1;
for(i=l;i>=1;--i){
if (ans!=-1) break;
for(j=s[i]-1;j>=0;--j){
if (ans!=-1) break;
if (i==1&&j==0) break;
work(i,j);
}
}
if (ans==-1){
if (l==1) ans=0;
else{
ans=0;
for(i=1;i<l;++i){
ans=ans*10+9;
}
}
}
printf("%lld\n",ans);
}
return 0;
}