标签:
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 (<=10000) 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. Do not output leading zeros.
Sample Input:
5 32 321 3214 0229 87
Sample Output:
22932132143287
思路:利用string 更好的解决此问题,非常好。尤其是A+B<B+A。
1 #include <iostream> 2 #include <string> 3 #include <algorithm> 4 #define MAX 10010 5 using namespace std; 6 7 struct Record 8 { 9 string str; 10 }Record[MAX]; 11 bool cmp(struct Record A,struct Record B) 12 { 13 return A.str+B.str<B.str+A.str; 14 } 15 16 int main() 17 { 18 int n; 19 cin>>n; 20 for(int i=0;i<n;i++) 21 cin>>Record[i].str; 22 23 sort(Record,Record+n,cmp); 24 /* 25 for(int i=0;i<n;i++) 26 { 27 if(i==0) 28 { 29 int j=0; 30 for(;j<Record[i].str.length();j++) 31 { 32 if(Record[i].str[j]!=‘0‘) 33 { 34 break; 35 } 36 } 37 for(;j<Record[i].str.length();j++) 38 { 39 putchar(Record[i].str[j]); 40 } 41 } 42 else 43 cout<<Record[i].str; 44 }*/ 45 46 string ans; 47 for(int i=0;i<n;i++) 48 { 49 ans+=Record[i].str; 50 } 51 //去除前导0 52 while(ans.size()>0&&ans[0]==‘0‘) 53 { 54 ans.erase(ans.begin()); 55 } 56 if(ans.size()==0) 57 cout<<0; 58 else 59 cout<<ans; 60 putchar(‘\n‘); 61 return 0; 62 }
PAT1038. Recover the Smallest Number
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4294255.html