原题
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 integerN(≤104) followed byNnumber 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
结尾无空行
思路
用字符串读取输入的数据(除第一项),然后按字典序(特殊情况下特殊处理)排序再输出。
通过代码
#include <bits/stdc .h> #include <string> using namespace std; vector<string> str(10001); bool cmp(string a,string b){ return a b<b a; } int main(){ string result; int n; cin>>n; for(int i=0;i<=n-1;i ){ cin>>str[i]; } sort(str.begin(),str.begin() n,cmp); for(int i =0 ;i<=n-1;i ){ result =str[i]; } while(result[0]=='0'){ result.erase(result.begin() 0); } if(result.empty()){ cout<<'0'; } else{ cout<<result; } return 0; }
总结
知识
1.vector的用法,见https://blog.csdn.net/qq_45520030/article/details/119837736?spm=1001.2014.3001.5501
2.string理解,总结地点同上。
方法
1.一开始,0的处理存在问题。首先,我只删除了结尾开头可能出现的0。后来,我发现可能有不止一个0重写代码,直到它不是0,但我忽略了在所有0的情况下需要输出一个0。以后考虑极限时请假设“没有xx怎么办?xx怎么办”,“全是xx怎么办”。
2.一开始忽略了这个问题中并不是所有的字符串都应该按字典顺序排序,比如32和32103,按字典顺序排列32更小,但如果把32排在前面,3232103明显大于3210332。
意识到这一点后,我想比较两个数a、b首先比较长度重叠的部分。如果长度重叠的部分相等,则比较长方超出的部分和短方。例如,上一个例子首先比较32和32,然后比较32和103。显然,103更小,所以32103更高。我认为思维没有问题,但总有一个测试用例不能通过(sort函数的cmp参数代码如下(复杂的另一个原因是无用string))。
bool cmp(char a[],char b[]){ int an=strlen(a),bn=strlen(b); int special=0; if(an>bn){ return (!cmp(b,a)); } else if(an<bn){ for(int i=0;i<an;i ){ if(a[i]!=b[i]) { special=0; break; } special=1; } if(special){ for(int i=an,j=0;i<bn;i ,j ){ if(a[j]>b[i]){ return false; } } } } return (string)a<(string)b; }
在阅读了其他朋友的代码后,我发现了更简单的方法,即直接比较a b和b a谁大就好。
bool cmp(string a,string b){ return a b<b a; }
下次遇到类似情况,请先在草稿纸在草稿纸上,然后根据目的考虑是否有简单的方法。
3.我一直把数字作为字符串来处理,但当我开始写判断句子时,我把0作为比较,我必须注意我应该使用数字或字符串。
心态
看到简单的问题别骄傲(敲头三下呜呜)。