今天比较忙,没什么状态做题
只做了一些练练手感
最小字符串
问题描述
给定一些字符串(只包含小写字母),要求将他们串起来构成一个字典序最小的字符串。
输入格式
第一行T,表示有T组数据。
接下来T组数据
每组第一行一个正整数n,表示字符串个数。
接下来n行,每行一个字符串(长度不超过100)。
输出格式
T行,每行一个字符串。
样例输入
1
3
a
b
c
样例输出
abc
数据规模和约定
T<=7000,n<=100;
这样例给了还不如不给
一眼看去还以为是对字符串排序后加起来()
然后一个都没对
看了样例发现相距甚远
发现b ,ba这两个数据b在前面而+起来bba>bab
然后又尝试贪心
用双指针last 和pre保存目前总结果和新加进来的字符串
那个小用哪种
#include<iostream>
#include<string>
#include<cctype>
#include<vector>
#include<map>
#include<algorithm>
#include<set>
using namespace std;
int main()
{
int n;
cin>>n;
while(n--)
{
string temp;
int t;
cin>>t;
string sum="";
string pre;
string last;
cin>>pre;
while(--t)
{
cin>>last;
if(pre+last>last+pre)
{
last=last+pre;
}
else
{
last=pre+last;
}
pre=last;
}
for(int i=0;i<pre.length();i++)
{
cout<<pre[i];
}
cout<<endl;
getchar();
}
return 0;
}
当然还是想错了,我也觉得很奇怪,应该没什么问题才对
然后借鉴了一下大佬的博客
发现居然是我排序错了
要按照一个奇奇怪怪的cmp法则排序
个人理解为按照两个字符串相加那种在前排序小就放在前面
bool cmp(string a, string b)
{
string t1=a+b,t2=b+a;
if(t1 < t2)
return true;
else
return false;
}
个人感觉写成a+b<b+a就好了,还容易理解
实际上也确实可以
#include<iostream>
#include<string>
#include<cctype>
#include<vector>
#include<map>
#include<algorithm>
#include<set>
using namespace std;
bool cmp(string a, string b)
{
return a+b<b+a;
}
int main()
{
std::ios::sync_with_stdio(0);
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
string sum="";
string temp[n];
for(int i = 0; i < n; i++)
cin >> temp[i];
sort(temp,temp+n,cmp);
for(int i = 0; i < n; i++)
sum += temp[i];
cout << sum << endl;
}
return 0;
}