1. 程式人生 > >PAT 1038 Recover the Smallest Number[dp][難]

PAT 1038 Recover the Smallest Number[dp][難]

class div msu ron 遇到 size ati cat math

1038 Recover the Smallest Number (30 分)

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

題目大意:給出幾個數,要求求出它們的片段拼接,並且這個數是所有數中最小的。

//一看到就不太明白怎麽做,拼接不同總長度也不一定相同,有0開頭的,如果放在中間的話就算是中間一位了。沒什麽思路,考試遇到這個的話會跪。

代碼來自:https://www.liuchuo.net/archives/2303

#include <iostream>
#include <string>
#include <algorithm>
using
namespace std; bool cmp0(string a, string b) {//兩個相同的數相加,它們的長度肯定是相同的。 return a + b < b + a; } string str[10010];//使用字符串數組! int main() { int n; scanf("%d", &n); for(int i = 0; i < n; i++) cin >> str[i];//以String作為輸入。 sort(str, str + n, cmp0); string s; for(int i = 0; i < n; i++) s += str[i];//將字符串拼接。 while(s.length() != 0 && s[0] == 0) s.erase(s.begin());//將開頭的0除去。 if(s.length() == 0) cout << 0; cout << s; return 0; }

//柳神的代碼簡直嘆為觀止。厲害了,學習了。

1.對字符串的處理,關鍵是這個cmp0函數的使用。

PAT 1038 Recover the Smallest Number[dp][難]