错误写法:贪心算法
•先对N个字符串按字典序排序
•后从小到大拼在一起
•如:a ac ab 排序后就是 a ab ac
•最后的字符串即是 aabac
•又如:b ac bd abc 排序后是 abc ac b bd
•最后的字符串即是 abcacbbd
•
•但是,这个是
错误的!
•反例:b ba
•bba?
•bab!
正确写法为:
#include "iostream"
#include "algorithm"
#include"string"
using namespace std;
bool cmp(string s1,string s2){
return s1+s2 <s2+s1; //这是这个题目的关键
}
int main()
{
int T,n;
cin>>T;
while (T--)
{
cin>>n;
string *str = new string[n];
string result;
//输入
for (int i = 0;i < n;i++)
{
cin>>str[i];
}
sort(str,str + n,cmp);//全排列
for (int i = 0;i < n;i++)
{
result += str[i];
}
cout<<result<<endl;
}
//system("pause");
return 0;
}