492 字
2 分钟
Ashmal

题面#

You have an array aa of nn strings a1,a2,,ana_{1}, a_{2}, \ldots, a_{n}, each consisting of lowercase English letters, and an empty string ss.

In the ii-th (1in1 \le i \le n) step, you should do one of the following:

  • add aia_{i} to the beginning of ss, or
  • add aia_{i} to the end of ss.

For example, if before the ii-th step s=abas = \mathtt{aba} and ai=bbaa_{i} = \mathtt{bba}, after the ii-th step, ss will be equal to ababba\mathtt{ababba} or bbaaba\mathtt{bbaaba}.

What’s the lexicographically smallest string ss you can reach after nn steps?

A string aa is lexicographically smaller than a string bb of the same length, if and only if the following holds:

  • in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb.

Input

Each test contains multiple test cases. The first line contains the number of test cases tt (1t5001 \le t \le 500). The description of the test cases follows.

The first line of each test case contains a single integer nn (1n10001 \le n \le 1000) — size of array aa. The next line contains nn strings a1,a2,,ana_{1}, a_{2}, \ldots, a_{n} (1ai40001 \le |a_i| \le 4000), each consisting of lowercase English letters.

It is guaranteed that the sum of nn over all test cases does not exceed 10001000, and the total length of all strings in the input (over all test cases) does not exceed 40004000.

Output

For each test case, print the lexicographically minimum string ss you can reach after nn steps.

思路#

设处理到第 ii 步后的当前字符串为 ss,本步只有两种选择 ai+sa_i+ss+ais+a_i,目标是使最终字符串字典序最小

关键性质 若 xyx \le y(字典序),则对任意固定字符串 cccxcycx \le cyxcycxc \le yc,即同前缀或同后缀拼接保持字典序

因此对固定 aia_i,函数 F(s)=min(ai+s, s+ai)F(s)=\min(a_i+s,\ s+a_i) 关于 ss 单调不减

bestibest_i 为前 ii 个字符串操作后可达的字典序最小结果,有递推: besti=min(besti1+ai, ai+besti1)best_i = \min\left(best_{i-1}+a_i,\ a_i+best_{i-1}\right)

NOTE

证明

用归纳,任取上一步可达的任意 ss,都有 besti1sbest_{i-1}\le s,由单调性得 F(besti1)F(s)F(best_{i-1})\le F(s),故本步从最小状态转移得到的即为全局最小
算法 初始化 s=ϵs=\epsilon,依次读入 aia_i 并令 s=min(s+ai, ai+s)s=\min(s+a_i,\ a_i+s),输出最终 ss
复杂度 设该测试用例总字符数为 LL,每步构造并比较两次拼接,整体可视为 O(nL)O(nL),在约束 L4000\sum L \le 4000 下足够

Ashmal
https://github.com/posts/ashmal/
作者
FZSGBall
发布于
2026-05-14
许可协议
CC BY-NC-SA 4.0