PAT 1038 Recover the Smallest Number 贪心

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given { 32, 321, 3214, 0229, 87 }, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (≤10​4​​) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the smallest number in one line. Notice that the first digit must not be zero.

Sample Input:

5 32 321 3214 0229 87

Sample Output:

22932132143287

想让结果最小很容易想到贪心算法,将各串数字按序排列输出即可。做题时想的比较复杂,两串字符串公共长度处依次比较字典序后,再将剩余字符串不断取余比较,虽然结果正确,但浪费不少时间。题解的方法非常简便,对数字串S1、S2,若S1+S2<S2+S1,则S1排在S2前面,否则排在S2后面。

题解方法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

class Cmp implements Comparator<String>{

	@Override
	public int compare(String o1, String o2) {
		return (o1+o2).compareTo(o2+o1);
	}
	
}
public class Main {

	
    public static void main(String[] args) throws IOException {
    	BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));

    	String[] line=reader.readLine().split(" ");
    	int N=Integer.valueOf(line[0]);
    	
    	Arrays.sort(line,1,line.length,new Cmp());

    	StringBuilder sb=new StringBuilder();
    	for(int i=1;i<line.length;i++) {
    		sb.append(line[i]);
    	}
    	String ans=sb.toString();
    	//找出第一个不为0的数
    	int begin=0;
    	while(begin<ans.length()) {
    		if(ans.charAt(begin)!='0') 
    			break;
    		begin++;    		
    	}
    	if(begin==ans.length())
    		System.out.println(0);
    	else {
    		System.out.println(ans.substring(begin));
    	}
    }
}

我的比较函数:


class Cmp implements Comparator<String>{

	@Override
	public int compare(String o1, String o2) {
		int len=Math.min(o1.length(),o2.length());
		int i=0;
		while(i<len) {
			//公共长度部分升序排序
			if(o1.charAt(i)!=o2.charAt(i))
				return o1.charAt(i)-o2.charAt(i);
			i++;
		}
		//取余比较
		if(o1.length()==o2.length()) {
			return 0;
		}else if(o1.length()>o2.length()) {
			return compare(o1.substring(i), o2);
		}else {
			return compare(o1, o2.substring(i));
		}
	}
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章