Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

贪心策略,我来解释一下

Posted by yzhw at 2010-07-24 13:37:00 on Problem 2325
首先,这题要用高精度,我用的Java,可以偷懒下~
如果原数不为1,则依次从9-0扫描能否整除它,如果可以的话将i放入栈,继续此步骤直到原数为1。判断如果栈中元素数<2的话则将1压栈。然后逆向输出数字即可。具体细节看我程序吧,没写注释,但是感觉结构很清楚~~

Source Code

Problem: 2325  User: yzhw 
Memory: 5448K  Time: 375MS 
Language: Java  Result: Accepted 

Source Code 
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException{
		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
		BigInteger stdnum[]=new BigInteger[10];
		stdnum[0]=new BigInteger("0");
		stdnum[1]=new BigInteger("1");
		for(int i=2;i<10;i++)
			stdnum[i]=stdnum[i-1].add(stdnum[1]);
		Stack <Integer>ans=new Stack();
		while(true)
		{
			String str=in.readLine();
			if(str.compareTo("-1")==0)
				break;
		
		   BigInteger num=new BigInteger(str);
		   if(num.equals(stdnum[0]))
		   {
			   System.out.println(10);
			   continue;
		   }
		   else if(num.equals(stdnum[1]))
		   {
			   System.out.println(11);
			   continue;
		   }
		  // ans.clear();
		   boolean flag=false;
		   while(!num.equals(stdnum[1]))
		   {
			   flag=false;
			   for(int i=9;i>1;i--)
				   if(num.mod(stdnum[i]).equals(stdnum[0]))
				   {
					   flag=true;
					   num=num.divide(stdnum[i]);
					   ans.push(i);
					   break;
				   }
			   if(!flag) break;
		   }
		   if(!flag)
		   {
			   System.out.println("There is no such number.");
			   ans.clear();
		   }
		   else
		   {
			   while(ans.size()<2)
				   ans.push(1);
			   while(!ans.empty())
			   {
				   System.out.print(ans.pop());
			   }
			   System.out.println();
		   }
		   
			
			
		}

	}

}


Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator