1. 程式人生 > >2016 CCPC 長春

2016 CCPC 長春

題意:給出長度為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();
	}
}