Description
汤汤不小心把VIP顾客的资料卡碰洒了,散落一地,之前是按顾客姓名的字典序排列的,所以必须要重新整理
为了减轻工作量,她先把资料卡分了两份,让自己的店员小明和小红分别按字典序升序分别整理好,她再合并在一起整理。
不允许使用C++的sort函数
Input
第一行,整数t,表示含t 组测试数据
第二行,输入整数 n1,之后输入 n1 个顾客姓名,表示小明整理好的顾客资料卡,已按字典序升序排列;
第三行,输入整数 n2,之后输入 n2 个顾客姓名,表示小红整理好的顾客资料卡,已按字典序升序排列:
以此类推输入多组数据。
Output
先输出合并后的资料卡总数,再依次输出按字典序升序排列的顾客姓名,用空格分隔;
每组数据之间用空行分开,具体格式参考样例。
Sample
Input
1
3 Jerry Tom Tuffy
4 Anna Jack Peter Rose
Output
7 Anna Jack Jerry Peter Rose Tom Tuffy
下面是本题C++题解:
#include <iostream>
#include <vector>
// 合并两个已排序的姓名列表,并按字典序升序排列
std::vector<std::string> mergeAndSort(const std::vector<std::string>& list1, const std::vector<std::string>& list2) {
std::vector<std::string> mergedList;
size_t i = 0, j = 0;
// 合并两个列表
while (i < list1.size() && j < list2.size()) {
if (list1[i] < list2[j]) {
mergedList.push_back(list1[i]);
++i;
}
else {
mergedList.push_back(list2[j]);
++j;
}
}
// 处理剩余元素
while (i < list1.size()) {
mergedList.push_back(list1[i]);
++i;
}
while (j < list2.size()) {
mergedList.push_back(list2[j]);
++j;
}
return mergedList;
}
int main() {
int t;
std::cin >> t;
while (t--) {
int n1, n2;
std::cin >> n1;
std::vector<std::string> list1(n1);
for (int i = 0; i < n1; ++i) {
std::cin >> list1[i];
}
std::cin >> n2;
std::vector<std::string> list2(n2);
for (int i = 0; i < n2; ++i) {
std::cin >> list2[i];
}
// 合并并按字典序升序排列
std::vector<std::string> mergedAndSorted = mergeAndSort(list1, list2);
// 输出结果
std::cout << mergedAndSorted.size() << " ";
for (const auto& name : mergedAndSorted) {
std::cout << name << " ";
}
std::cout << "\n" << std::endl;
}
return 0;
}