题目
You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.
Given the list of strings, output the lexicographically smallest concatenation.
Input
The first line contains integer n — the number of strings (1 ≤ n ≤ 5·104).
Each of the next n lines contains one string ai (1 ≤ |ai| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·104.
Output
Print the only string a — the lexicographically smallest string concatenation.
Examples
Input
4 abba abacaba bcd er
Output
abacabaabbabcder
Input
5 x xx xxa xxaa xxaaa
Output
xxaaaxxaaxxaxxx
Input
3 c cb cba
Output
cbacbc
题意
给定n个字符串,在这n个字符串的排列中,输出字典序最小的那个。
分析
既然输出字典序最小的,那就从小到大排序输出就ok了。可关键是,怎么将这些字符串排序,如果只是单纯的sort一下,那么,字符串"x",显然比字符串"aa"大,所以就是"aax",但实际应该输出的是"aax",所以不能直接sort。可以让这些字符串两两结合,然后再排个序,就可以了。
代码
#include<iostream>
#include<cstdio>
#include<string.h>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<cmath>
#include<algorithm>
#include<vector>
#include<stdlib.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f
const int N=5e4+5;
struct node{
string t;
}s[N];
bool cmp(node m,node n)
{
return m.t+n.t<n.t+m.t;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
cin>>s[i].t;
}
sort(s,s+n,cmp);
for(int i=0;i<n;i++)
cout<<s[i].t;
cout<<endl;
return 0;
}
本文介绍了一种算法,用于解决给定多个字符串时如何排列它们以形成字典序最小的组合字符串。通过自定义比较函数和排序算法,可以有效地找到最优解。

309

被折叠的 条评论
为什么被折叠?



