解法一:排序
先要按照输入数据构建链表,因为可能会有无效结点。
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
string address;
int key;
string next;
};
bool cmp(Node &o1, Node &o2) {
return o1.key < o2.key;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N;
string head;
cin >> N >> head;
vector<Node> list;
map<string, Node> nodeMap;
for (int i = 0; i < N; ++i) {
Node node;
cin >> node.address >> node.key >> node.next;
nodeMap.emplace(node.address, node);
}
while (head != "-1") {
auto res = nodeMap.find(head);
list.emplace_back(res->second);
head = res->second.next;
}
if (list.empty()) {
cout << "0 -1\n";
return 0;
}
sort(list.begin(), list.end(), cmp);
for (int i = 0; i < list.size() - 1; ++i) {
list[i].next = list[i + 1].address;
}
list[list.size() - 1].next = "-1";
cout << list.size() << " " << list[0].address << "\n";
for (auto &it:list) {
cout << it.address << " " << it.key << " " << it.next << "\n";
}
}