PAT-A-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

巧妙,絕對的巧妙!

一道看起來很簡單,寫起來有點痛苦,最後解法比較有趣的題目。

這道題最關鍵的地方在於,怎麼定義排序規則是的字符串連接起來表達的整數最小。

按照sort默認的對string排序不能解決問題,比如樣例:排序以後是229、32、321、324、89.但是如果按照這個順序輸出,即先輸出32,在輸出321即這部分排列爲32321,這個順序一定比先輸出321,在輸出32即32132大。所以我們必須對sort的排序方法進行定義。

要求輸出順序使得表達的數最小,也就是說,任何兩個連續的string,交互位置以後得到的值都會變大,that means,任意兩個位置的字符串連接起來和最小,也就是a+b<b+a  

再然後就是細節問題了,看到案例中的0229,作爲開頭一定要丟掉0。

把所有的字符串連接在一起,從頭開始遍歷,計算連續的0的個數,直到碰到第一個不是0的數字結束掉。

如果連續0的個數等於字符串的長度,也就是說整個串都是0

#include <iostream>
#include <vector>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(const string s1,const string s2){
	return s1+s2<s2+s1;
}
int main(){
	int n,i;
	scanf("%d",&n);
	string temp;
	vector<string> data;
	for(int j=0;j<n;j++){
		cin>>temp;
		data.push_back(temp);
	}
	sort(data.begin(),data.end(),cmp);
	string out;
	for (i=0;i<n;i++)
	    out += data[i];
	for (i=0;i<out.size()&&out[i]=='0';i++);
	if (i==out.size())
		 printf("0");
	else 
      printf("%s",out.c_str()+i);
	printf("\n");
	return 0;
	
}

 

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