题意:给定一个不大于 10^1000的正整数ss,构造不超过5050个回文数,使得这些数之和恰好是ss。
题解:每次用不超过ss的最大回文数去减ss,这样ss的位数会减半,需要实现一个高精度减法。
直接java..
这波java打的抛异常抛的我心累。
要注意到
string里改变一个字符比较麻烦。
可以先存如char[]数组,但是char[]数组变成string数组再变为BigInteger的时候,要保证char数组后面都是有值的,所以要动态开内存。
其他地方都是细节了。
import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int t=in.nextInt();
for(int cas=1;cas<=t;cas++)
{
System.out.println("Case #" + cas + ":");
String str=in.next();
BigInteger res=new BigInteger(str);
if (res.compareTo(BigInteger.TEN) < 0)
{
System.out.println(1);
System.out.println(res);
continue;
}
BigInteger ans[]=new BigInteger[55];
int tttt=0;
while(true)
{
int cnt = 0, flag = 0;
char a[]=res.toString().toCharArray();
int n = res.toString().length();
char s[]=new char[n];
for (int i = 0; i < n; i++) s[i] = '0';
int cc = 0;
if (a[0] == '1')
cc = 1;
for (int i = 1; i < n; i++) {
if (cc == 0)
break;
if (a[i] != '0')
cc = 0;
}
if (cc == 1)
s[n - 1] = '1';
else {
for (int i = 0; i <= n / 2 && i <= n - i - 1; i++) {
if (n % 2 == 1 && i == n - i - 1) {
if (a[i] == '0' && flag == 1) {
s[i + cnt] = '1';
a[i + cnt + 1]--;
} else {
if (flag == 1)
a[i]--;
}
break;
} else if (n % 2 == 0 && i + 1 == n - i - 1) {
if (a[i] == '0' && a[i + 1] == '0' && flag == 1) {
s[i + cnt + 1] = '1';
a[i + cnt + 2]--;
} else {
if (a[i] >a[i + 1])
a[i]--;
else if(a[i]==a[i+1]&&flag==1)
a[i]--;
a[i + 1] = a[i];
}
break;
}
if (i >= n - i - 1)
break;
if (a[i] < a[n - 1 - i]) {
flag = 0;
a[n - i - 1] = a[i];
} else if (a[i] == a[n - 1 - i]) {
;
} else {
a[n - i - 1] = a[i];
flag = 1;
}
if (a[i] == '0')
cnt++;
else cnt = 0;
}
}
// System.out.println(a);
// System.out.println(s);
BigInteger a1 = new BigInteger(String.valueOf(a));
BigInteger a2 = new BigInteger(String.valueOf(s));
// System.out.println("a1="+a1);
// System.out.println("a2="+a2);
a1 = a1.subtract(a2);
// System.out.println("a1-a2="+a1);
ans[tttt] = a1;
tttt++;
res = res.subtract(a1);
// System.out.println(res);
if (res.compareTo(BigInteger.TEN) < 0)
{
ans[tttt] = res;
tttt++;
if(res.compareTo(BigInteger.ZERO) ==0)
tttt--;
break;
}
}
System.out.println(tttt);
for(int i=0;i<tttt;i++)
System.out.println(ans[i]);
}
}
}