解法一:链表+Map

Map 存储结点,进一步构造结点链表,找出有两个前序的结点即为公共后缀的起点。
注意考虑两个字符串的头结点一致的边界情况。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class Node {
  4. public:
  5. string address;
  6. char data;
  7. string next_address;
  8. Node *next;
  9. Node *pre;
  10. Node(string address, char data, string next_address) : address(address),
  11. data(data),
  12. next_address(next_address),
  13. pre(nullptr) {}
  14. };
  15. map<string, Node> nodeMap;
  16. int main() {
  17. string first, last;
  18. int N;
  19. cin >> first >> last >> N;
  20. string address, next;
  21. char data;
  22. for (int i = 0; i < N; ++i) {
  23. cin >> address >> data >> next;
  24. nodeMap.emplace(address, Node(address, data, next));
  25. }
  26. if (first==last) {
  27. cout << first << '\n';
  28. return 0;
  29. }
  30. for (auto &it:nodeMap) {
  31. auto nextPair = nodeMap.find(it.second.next_address);
  32. if (nextPair != nodeMap.end()) {
  33. it.second.next = &nextPair->second;
  34. if (nextPair->second.pre == nullptr) {
  35. nextPair->second.pre = &it.second;
  36. } else {
  37. cout << nextPair->second.address << '\n';
  38. return 0;
  39. }
  40. } else {
  41. it.second.next = nullptr;
  42. }
  43. }
  44. cout << "-1\n";
  45. }