Problem
Dr lee cuts a string S into N pieces,s[1],…,s[N].
Now, Dr lee gives you these N sub-strings: s[1],…s[N]. There might be several possibilities that the string S could be. For example, if Dr. lee gives you three sub-strings {“a”,“ab”,”ac”}, the string S could be “aabac”,”aacab”,”abaac”,…
Your task is to output the lexicographically smallest S.
Input
The first line of the input is a positive integer T. T is the number of the test cases followed.
The first line of each test case is a positive integer N (1 <=N<= 8 ) which represents the number of sub-strings. After that, N lines followed. The i-th line is the i-th sub-string s[i]. Assume that the length of each sub-string is positive and less than 100.
Output
The output of each test is the lexicographically smallest S. No redundant spaces are needed.
Sample input
1
3
a
ab
ac
Sample output
aabac
大意是给一组字符串, 把它们连接成一个字典次序最小的串, 一开始想法是按字典顺序sort这组字符串,也就是用STL中的string类中默认的比较(运算符i.e. >)函数, 可是这样的结果是wrong answer, 想出了一个(类)反例, 也可能是这种方法的唯一(类)的反例, 就是给你一组 'fu', 'fuck', 假如直接按字典顺序排序的话, 合成的字符串将是“fufuck”..
因为("fu"<"fuck")...而很明显("fuckfu"<"fufuck")..
所以需要改变那个比较函数, 定义一个string类的比较函数,
A < B if ( A+B < B +A) // ( A,B是字符串 ‘+’是指字符串连接)
else A > B...
实现中用到 STL中的sort, 跟string, 代码不用很长
代码如下,
//
substring
#include
<
vector
>
#include
<
algorithm
>
#include
<
iostream
>
#include
<
string
>
using
namespace
std;
bool
str_cmp(
string
s1,
string
s2)
...
{
return (s1+s2<s2+s1);
}
int
main()
...
{
int t, str_num, i, j;
cin>>t;
for(i=0; i<t; i++)
...{
vector<string> str;
vector<string>::iterator itr;
cin>>str_num;
string temp;
for(j=0; j<str_num; j++)
...{
cin>>temp;
str.push_back(temp);
}
sort(str.begin(), str.end(), str_cmp);
for(itr=str.begin(); itr!=str.end(); itr++)
...{
cout<<*itr;
}
cout<<endl;
}
return 0;
}