CodeForces - 632C - The Smallest String Concatenation(思维)

CodeForces - 632C - The Smallest String Concatenation

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个字符串,题目要求让你想一种方式将这些字符串连接在一起,使得他们的字典序最小。

其实当时刚读完题,表示一脸懵逼,字典序?字符串怎么看字典序?后来看到题解,恍然大悟,原来还有strcmp函数嘛,这个函数是可以比较两个字符串的大小,是按照字典序排列的。这样的话,你就可以将读入的字符串进行排序了。什么?字符串还排序?额,可以自己写函数啊,你把两个字符串拼接在一起,看哪一种方式的字典序小,就按照小的方式排列。

AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct node
{
    char s[220];//刚开始开小了,一直RE
}t[510000];

bool cmp(node a, node b)
{
    return strcmp(strcat(a.s, b.s), strcat(b.s, a.s)) < 0;
}

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        for(int i = 0; i < n; i++)
            scanf("%s", t[i].s);
        sort(t, t + n, cmp);
        for(int i = 0; i < n; i++)
            printf("%s", t[i].s);
        printf("\n");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/81813324
今日推荐