#include <iostream> #include <unordered_map> #include <vector> using namespace std; int main() { // 存储每个节点的父节点和子节点 unordered_map<char, char> parent; unordered_map<char, vector<char>> children; // 读入数据 string line; while (getline(cin, line)) { char p = line[0]; char c = line[2]; parent[c] = p; children[p].push_back(c); } // 找到根节点 char root; for (auto& it : parent) { if (parent.find(it.second) == parent.end()) { root = it.second; break; } } // 先根遍历 vector<char> stack{root}; while (!stack.empty()) { char node = stack.back(); stack.pop_back(); cout << node << " "; if (children.find(node) != children.end()) { for (char child : children[node]) { stack.push_back(child); } } } return 0; }
时间: 2024-02-14 10:10:29 浏览: 148
这段代码已经非常简洁了,但是还有一些可以优化的地方:
1. 使用 auto 关键字可以简化代码。
2. 可以使用引用遍历 unordered_map,可以避免拷贝 map 中的数据。
3. 可以使用 emplace_back 函数来向 vector 中添加元素,可以避免拷贝元素。
4. 可以使用范围 for 循环来遍历 vector。
优化后的代码如下:
```
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
// 存储每个节点的父节点和子节点
unordered_map<char, char> parent;
unordered_map<char, vector<char>> children;
// 读入数据
string line;
while (getline(cin, line)) {
auto p = line[0], c = line[2];
parent[c] = p;
children[p].emplace_back(c);
}
// 找到根节点
char root;
for (auto& [child, par] : parent) {
if (parent.find(par) == parent.end()) {
root = par;
break;
}
}
// 先根遍历
vector<char> stack{root};
while (!stack.empty()) {
auto node = stack.back();
stack.pop_back();
cout << node << " ";
if (auto& children_vec = children[node]; !children_vec.empty()) {
for (auto child : children_vec) {
stack.emplace_back(child);
}
}
}
return 0;
}
```
希望对您有所帮助。
阅读全文
相关推荐

















“复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
#include<stack>
#include<vector>
int main() {
int m,n;
cin>>m>>n;
stack<vector<char>>ch;
for(int i=0;i<m;i++) {="" vector<char="">a(n, '\0');
for (int j = 0; j < n; j++)
{
cin >> a[j];
}
ch.push(a);
}
while(!ch.empty())
{
vector<char>b=ch.top();
ch.pop();
for(vector<char>::reverse_iterator it=b.rbegin();it!=b.rend();it++)
cout<<*it;
cout<<endl; }="" 64="" 位输出请用="" printf("%lld")<="" pre=""></endl;></char></char></m;i++)></vector<char></vector></stack></iostream>
”给我翻译成C++语言
#include <iostream>
using namespace std;
#include<stack>
#include<vector>
int main() {
int m,n;
cin>>m>>n;
stack<vector<char>>ch;
for(int i=0;i<m;i++) {="" vector<char="">a(n, '\0');
for (int j = 0; j < n; j++)
{
cin >> a[j];
}
ch.push(a);
}
while(!ch.empty())
{
vector<char>b=ch.top();
ch.pop();
for(vector<char>::reverse_iterator it=b.rbegin();it!=b.rend();it++)
cout<<*it;
cout<<endl; }="" 64="" 位输出请用="" printf("%lld")<="" pre=""></endl;></char></char></m;i++)></vector<char></vector></stack></iostream>

