版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/sdau20163942/article/details/83618966
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5920
题意:给出长度为1000的10进制数n,让你用小于50个回文数来组成n。
解析:考虑怎么构造较大的且尽可能接近n的回文串?拿出串n的前半部分,将其-1,然后对折到后半部分形成的回文数就是较为合适的一个累加项。然后减去这个累加项,递归处理差就好。然后对于100以内的数特殊处理作为递归边界。
JAVA代码(530ms):
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
static int step;
static String ans[]=new String[55];
static void work1(BigInteger s)
{
if(s.compareTo(BigInteger.valueOf(0))==0) return;
BigInteger ts=s;
String str=null;
char ch[]=new char[1005];
str=s.toString();
int len=str.length();
if(len==2)
{
if(s.compareTo(BigInteger.valueOf(20))>=0)
{
BigInteger sa=s.divide(BigInteger.valueOf(10));
sa=sa.subtract(BigInteger.ONE);
sa=sa.multiply(BigInteger.valueOf(10)).add(sa);
step++;
ans[step]=sa.toString();
work1(s.subtract(sa));
}
else if(s.compareTo(BigInteger.valueOf(11))>0)
{
step++;
ans[step]="11";
step++;
ans[step]=s.subtract(BigInteger.valueOf(11)).toString();
}else
{
step++;
ans[step]="9";
step++;
ans[step]=s.subtract(BigInteger.valueOf(9)).toString();
}
return;
}else if(len==1){
step++;
ans[step]=str;
return;
}
BigInteger temp=BigInteger.ONE;
for(int i=1;i<=len/2;i++)
{
temp=temp.multiply(BigInteger.valueOf(10));
}
s=s.subtract(temp);
str=s.toString();
ch=str.toCharArray();
len=str.length();
for(int i=1;i<=len/2;i++)
{
ch[len-i]=str.charAt(i-1);
}
str="";
for(int i=0;i<len;i++)
{
str+=ch[i];
}
s=new BigInteger(str);
step++;
ans[step]=str;
if(ts.subtract(s).compareTo(BigInteger.ZERO)>0)
work1(ts.subtract(s));
}
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
BigInteger ss=null;
int T,cas=0;
T=cin.nextInt();
while(T--!=0)
{
ss=cin.nextBigInteger();
System.out.println("Case #"+(++cas)+":");
step=0;
work1(ss);
System.out.println(step);
for(int i=1;i<=step;i++)
{
System.out.println(ans[i]);
}
}
cin.close();
}
}