"蔚来杯"2022牛客暑期多校训练营3 C-Concatenation
作者:互联网
问题描述
NIO was the king of the OIN Kingdom.
He had NNN children and wanted to teach
them how to count. In the OIN Kingdom, pental is used in counting, so his
children can only use 0, 1, 2, 3, and 4 to represent a number.
One day, NIO asked his children to write down their favorite numbers. After
that, he came out with a problem: if he concatenated these numbers into a big
number, what is the smallest number he could get? However, this problem was too
hard for him to solve, so can you help him?
输入格式
The first line contains an integer N(1≤N≤2∗106), denoting the number of NIO's children.
Then follows N lines, each line contains a
string si
denotes the favorite number of the i th child. The string is composed of 0, 1, 2, 3, and 4, but may have leading zeros because NIO's children hadn't fully understood how to count.
输出格式
One integer denotes the smallest number NIO can get.
样例输入
5
121
1
12
00
101
样例输出
00101112112
提示
If you have designed an algorithm whose time complexity is O(∣S∣log∣S∣) or so, please think twice before submitting it. Any algorithm other than linear complexity is NOT supposed to pass this problem. But of course, you can have a try. If you do so, we wish you good luck.
题解
给定n个数字,将这些数字连接成一个大的数字,求连接后最小的数。
考虑将数字当成字符串排序,设其中两个字符串为s1,s2,假设s1,s2,前后的字符串位置都已经确定,则s1能排在s2的前面的条件是,s1+s2比s2+s1小,将此作为排序标准排序后按顺序将字符串接起来即可
本题数据较大容易超时,加上读入优化以加快运行速度
向学长学到的一个卡常加速技巧:对于更改排序规则的函数cmp,若形参使用指针可以直接改变实参的值而不用再复制一遍,从而减少运行时间
1 #pragma GCC optimize(2) 2 #include <algorithm> 3 #include <iostream> 4 #include <cstdio> 5 #include <string> 6 using namespace std; 7 int n; 8 string s[2000005]; 9 int read() 10 { 11 int s=0; 12 char ch=getchar(); 13 while (ch<'0' || ch>'9') ch=getchar(); 14 while (ch>='0' && ch<='9') 15 s=s*10+ch-'0',ch=getchar(); 16 return s; 17 } 18 bool cmp(string &s1,string &s2) 19 { 20 return s1+s2<s2+s1; 21 } 22 int main() 23 { 24 int i,j; 25 n=read(); 26 for (i=1;i<=n;i++) 27 cin>>s[i]; 28 sort(s+1,s+n+1,cmp); 29 for (i=1;i<=n;i++) 30 cout<<s[i]; 31 return 0; 32 }
标签:s2,ch,NIO,蔚来,s1,number,多校,Concatenation,children 来源: https://www.cnblogs.com/rabbit1103/p/16608346.html