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));
		}
	}
	
}

 

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