用C++main函数和unordered_map实现 Write a program to complete the following command: new id - create a specified sequence of Numbers for id (id < 200000) Add id num - to join the sequence of Numbers for id integer num merge id1 id2 - merger sequence number of id1 and id2, and make id2 empty unique id - remove repetitive element in the sequence id out id - from small to large, output the elements of sequence of Numbers for ids separated by Spaces Input The First Line is n which mean the number of the Command (n <= 200000). The next n lines are correct Command. You don't have to worry wrong input and id is int. Output Then output according the requirements. Sample Input 16 new 1 new 2 add 1 1 add 1 2 add 1 3 add 2 1 add 2 2 add 2 3 add 2 4 out 1 out 2 merge 1 2 out 1 out 2 unique 1 out 1 Sample Ouput 1 2 3 1 2 3 4 1 1 2 2 3 3 4 1 2 3 4
时间: 2024-01-05 19:04:30 浏览: 77
C++中main()函数说明
以下是使用C++和unordered_map实现的代码:
```c++
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
unordered_map<int, vector<int>> sequences; // 用unordered_map存储每个id对应的序列
void new_sequence(int id) {
sequences[id] = vector<int>(); // 创建一个空的序列
}
void add_number(int id, int num) {
sequences[id].push_back(num); // 将num添加到id对应的序列中
}
void merge_sequence(int id1, int id2) {
sequences[id1].insert(sequences[id1].end(), sequences[id2].begin(), sequences[id2].end()); // 将id2对应的序列合并到id1对应的序列中
sequences[id2].clear(); // 清空id2对应的序列
}
void unique_sequence(int id) {
sort(sequences[id].begin(), sequences[id].end()); // 排序
auto it = unique(sequences[id].begin(), sequences[id].end()); // 去重
sequences[id].erase(it, sequences[id].end()); // 删除重复元素
}
void output_sequence(int id) {
sort(sequences[id].begin(), sequences[id].end()); // 排序
for (int num : sequences[id]) {
cout << num << " "; // 输出id对应的序列中的元素
}
cout << endl;
}
int main() {
int n;
cin >> n;
while (n--) {
string command;
cin >> command;
if (command == "new") {
int id;
cin >> id;
new_sequence(id);
} else if (command == "add") {
int id, num;
cin >> id >> num;
add_number(id, num);
} else if (command == "merge") {
int id1, id2;
cin >> id1 >> id2;
merge_sequence(id1, id2);
} else if (command == "unique") {
int id;
cin >> id;
unique_sequence(id);
} else if (command == "out") {
int id;
cin >> id;
output_sequence(id);
}
}
return 0;
}
```
希望能够帮到你!
阅读全文