贪心算法,最核心的在于贪心策略上
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 (≤104) 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;
}