题目大意
给出一些数字字符串,现在要求将这些字符串连接,使得连接后的字符串最小
输入
每组包含一个测试用例, 每个用例会给一个正整数 N ≤ 1 0 4 N \leq 10^4 N≤104,然后跟着 N N N个长度不超过8的数字字符串
输出
对每个测试用例输出连接后所能得到的最小的字符串,要求第一位不能是0,如果全为0就只输出一个0
样例输入
5 32 321 3214 0229 87
样例输出
22932132143287
解析
先将字符串排序,排序的规则就是a+b<b+a
这样就保证排序后的字符串一定是最小的,然后再判断是否全为0,并按要求输出。
这题用Python会在最后一个测试点超时。
python(超时):
# -*- coding: utf-8 -*-
# @Time : 2019/6/2 15:12
# @Author : ValarMorghulis
# @File : 1038.py
import functools
def cmp(a, b):
x = a + b
y = b + a
return -1 if x < y else (0 if x == y else 1)
def solve():
s = input().split()
s.pop(0)
s.sort(key=functools.cmp_to_key(cmp))
print(int(''.join(s)))
if __name__ == "__main__":
solve()
c++(AC):
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<cmath>
#define inf 0xffffffff
using namespace std;
bool cmp(string a, string b)
{
return (a+b)<(b+a);
}
int main()
{
int n;
scanf("%d", &n);
string str[n+2];
for(int i=0; i<n; i++)
cin>>str[i];
sort(str, str+n, cmp);
string ans="";
for(int i=0; i<n; i++)
ans+=str[i];
while(ans[0]=='0' && ans.length()!=0)
ans.erase(ans.begin());
if(ans.length()==0)
printf("0\n");
else
cout<<ans<<endl;
return 0;
}