To store English words, one method is to use linked lists and store a word letter by letter. To save some space, we may let the words share the same sublist if they share the same suffix. For example, loading and being are stored as showed in Figure 1.

~A1032 Sharing - 图1

You are supposed to find the starting position of the common suffix (e.g. the position of i in Figure 1).

Input Specification:

Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positive N (≤105), where the two addresses are the addresses of the first nodes of the two words, and N is the total number of nodes. The address of a node is a 5-digit positive integer, and NULL is represented by −1.

Then N lines follow, each describes a node in the format:

  1. Address Data Next

whereAddress is the position of the node, Data is the letter contained by this node which is an English letter chosen from { a-z, A-Z }, and Next is the position of the next node.

Output Specification:

For each case, simply output the 5-digit starting position of the common suffix. If the two words have no common suffix, output -1 instead.

Sample Input1:

  1. 11111 22222 9
  2. 67890 i 00002
  3. 00010 a 12345
  4. 00003 g -1
  5. 12345 D 67890
  6. 00002 n 00003
  7. 22222 B 23456
  8. 11111 L 00001
  9. 23456 e 67890
  10. 00001 o 00010

Sample Output1:

  1. 67890

Sample Input2:

  1. 00001 00002 4
  2. 00001 a 10001
  3. 10001 s -1
  4. 00002 a 10002
  5. 10002 t -1

Sample Output2:

  1. -1

思路

本题属于静态链表题型,所以我们可以这样处理:

  1. 把链表写到一个顺序表(数组或向量)里;
  2. 从尾巴向头部寻找公共后缀;

这样操作会容易得多。


代码

本题测试点6未通过,可能是有独立于链表的结点。

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. typedef struct ndoe_st {
  5. int addr;
  6. char data;
  7. int next;
  8. } node_st;
  9. node_st myList[100001] = {0x0};
  10. int main() {
  11. int START_WORD1(0), START_WORD2(0), N(0);
  12. cin >> START_WORD1 >> START_WORD2 >> N;
  13. // Read list
  14. for(int i = 0; i < N; i++) {
  15. int _addr(0), _next(0);
  16. char _data(0);
  17. cin >> _addr >> _data >> _next;
  18. myList[_addr].addr = _addr;
  19. myList[_addr].data = _data;
  20. myList[_addr].next = _next;
  21. }
  22. // Copy list to a vector
  23. vector<node_st> Word1;
  24. vector<node_st> Word2;
  25. for(int i = START_WORD1; i >= 0; i = myList[i].next)
  26. Word1.push_back( myList[i] );
  27. for(int i = START_WORD2; i >= 0; i = myList[i].next)
  28. Word2.push_back( myList[i] ) ;
  29. // Walk two word vectors and find the common suffix
  30. int i = Word1.size()-1;
  31. int j = Word2.size()-1;
  32. while( Word1[i].addr == Word2[j].addr && i >= 0 && j >= 0 ) {
  33. i--;
  34. j--;
  35. }
  36. if( i == Word1.size()-1 ) puts("-1");
  37. else printf("%05d\n", Word1[i+1].addr);
  38. return 0;
  39. }