标签:
Time Limit: 1 secs, Memory Limit: 32 MB
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.
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.
The output of each test is the lexicographically smallest S. No redundant spaces are needed.
1 3 a ab ac
aabac
ZSUACM Team Member
这道题的思路比较简单,题目每次给出n个字符串,然后要求输出用这n个字符串组合成的字典序最小的字符串,字符串需全部使用且不能重复使用。
首先我们要知道如何判断组成字典序最小的组合顺序,由字符串a和b,如果a+b小于b+a,那么我们就选择b+a组合,反之则选择a+b组合,基于这样一种判断,我们可以直接定义一个cmp对所有字符串进行sort排序即可;
在cmp(const string &x1,const string &x2)中,我们只需返回x1+x2<x2+x1即可,那么我们最终得到的排序按顺序输出,就是题目所要求的字典序最小的字符串。
代码如下:
#include <iostream> #include <algorithm> using namespace std; string s[16]; bool cmp(const string &x1,const string &x2) { return x1+x2<x2+x1; } int main() { int t; cin>>t; while(t--) { int n; cin>>n; for(int i=0;i<n;i++) { cin>>s[i]; } sort(s,s+n,cmp); for(int i=0;i<n;i++) { cout<<s[i]; } cout<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/RiTianBigBrother/p/5309363.html