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(≤104)N (≤10^4)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
解題思路
題目大意: 給N個數字,然后組合成一個數字,求最小的組合。
解題思路: 這道題的關鍵在于,抽象出題目要求的排序規則,使用sort函數進行排序。我們不妨從Demo中總結一下——
顯然,小的要放前面,0229比3214要小,比更短的87也更小,比其他都要小,所以放最前面。這一點符合string的operator<規則,可以直接使用a<b。
但是麻煩的是, 并不是所有的字符串都符合這個規則,其中,3214比32要大,但是如果把3214放在32前面,顯然不是正確的選擇——
但如果 (a+b)<(b+a)的組合成立的話 ,我們發現,這幾乎符合所有的條件,我們可以得到最小的排序組合。根據sort的排序規則,如果符合規則(a+b)<(b+a),那么a和b保持原來的順序,否則交換順序。
此外,測試數據存在邊界情況,第二個測試點,最大的數據可能是0,此時要輸出0。
總結
這道題有一種大道至簡、返璞歸真的感覺,最開始總結規律,搞得很復雜,把排序規則寫的很冗余,但是還是通過了,后來參考了別人的代碼,發現原來可以如此簡潔,看來總結抽象的能力還是不夠。發現了規律了之后,其實并不難。這道題我學到了——
1) 使用stringstream轉換string到int,更快捷高效;
2) 發現規律,抽象建模很重要,或許這就是我們常說的解決問題的能力。
總結
以上是生活随笔為你收集整理的1038 Recover the Smallest Number (30 分)-字符串分段排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Facebook新研究:根据照片自动生成
- 下一篇: 夏新N820/N821 recovery