题目描述
输入一组字符串,用2-路归并排序按字典顺序进行降序排序。
输入
测试次数t
每组测试数据:数据个数n,后跟n个字符串,字符串不含空格。
输出
对每组测试数据,输出2-路归并排序的每一趟排序结果。每组测试数据的输出之间有1空行。
样例查看模式
正常显示
查看格式
输入样例1 <-复制
2
6 shenzhen beijing guangzhou futian nanshan baoan
10 apple pear peach grape cherry dew fig haw lemon marc
输出样例1
shenzhen beijing guangzhou futian nanshan baoan
shenzhen guangzhou futian beijing nanshan baoan
shenzhen nanshan guangzhou futian beijing baoan
pear apple peach grape dew cherry haw fig marc lemon
pear peach grape apple haw fig dew cherry marc lemon
pear peach haw grape fig dew cherry apple marc lemon
pear peach marc lemon haw grape fig dew cherry apple
- 开摆开摆我就是不合格的c++使用者。
#include <iostream>
#include <algorithm>
#include <string>
#include <deque>
using namespace std;
class node{
public:
string city;
int number;
node(){
city='0';number=0;
}
};
bool cmp(node a,node b){
if(a.number>b.number)
return 1;
else
return 0;
}
int main(){
int t;cin>>t;
while (t--){
int n;cin>>n;
deque<node>d;
for (int i = 0; i < n; ++i) {
node s;
cin>>s.city;s.number=(int)s.city[0];
d.push_back(s);
}
int gap=2;
while (gap<=n){
deque<node>s;
while (d.size()>=gap){
deque<node>q;
for (int i = 0; i < gap; ++i) {
q.push_back(d.front());
d.pop_front();
}
sort(q.begin(),q.end(),cmp);
while (!q.empty()){
s.push_back(q.front());
q.pop_front();
}
}
while (!d.empty()){
sort(d.begin(),d.end(),cmp);
s.push_back(d.front());
d.pop_front();
}
for (int i = 0; i < n-1; ++i) {
cout<<s[i].city<<" ";
}cout<<s[n-1].city<<endl;
for (int i = 0; i < n; ++i) {
d.push_back(s[i]);
}
gap*=2;
}
deque<node>s;
while (d.size()>=gap){
deque<node>q;
for (int i = 0; i < gap; ++i) {
q.push_back(d.front());
d.pop_front();
}
sort(q.begin(),q.end(),cmp);
while (!q.empty()){
s.push_back(q.front());
q.pop_front();
}
}
while (!d.empty()){
sort(d.begin(),d.end(),cmp);
s.push_back(d.front());
d.pop_front();
}
for (int i = 0; i < n-1; ++i) {
cout<<s[i].city<<" ";
}cout<<s[n-1].city<<endl;
cout<<endl;
}
}```