解法一:排序

先要按照输入数据构建链表,因为可能会有无效结点。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class Node {
  4. public:
  5. string address;
  6. int key;
  7. string next;
  8. };
  9. bool cmp(Node &o1, Node &o2) {
  10. return o1.key < o2.key;
  11. }
  12. int main() {
  13. ios::sync_with_stdio(false);
  14. cin.tie(0);
  15. int N;
  16. string head;
  17. cin >> N >> head;
  18. vector<Node> list;
  19. map<string, Node> nodeMap;
  20. for (int i = 0; i < N; ++i) {
  21. Node node;
  22. cin >> node.address >> node.key >> node.next;
  23. nodeMap.emplace(node.address, node);
  24. }
  25. while (head != "-1") {
  26. auto res = nodeMap.find(head);
  27. list.emplace_back(res->second);
  28. head = res->second.next;
  29. }
  30. if (list.empty()) {
  31. cout << "0 -1\n";
  32. return 0;
  33. }
  34. sort(list.begin(), list.end(), cmp);
  35. for (int i = 0; i < list.size() - 1; ++i) {
  36. list[i].next = list[i + 1].address;
  37. }
  38. list[list.size() - 1].next = "-1";
  39. cout << list.size() << " " << list[0].address << "\n";
  40. for (auto &it:list) {
  41. cout << it.address << " " << it.key << " " << it.next << "\n";
  42. }
  43. }