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.
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:
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:
11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010
Sample Output1:
67890
Sample Input2:
00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1
Sample Output2:
-1
思路
本题属于静态链表题型,所以我们可以这样处理:
- 把链表写到一个顺序表(数组或向量)里;
- 从尾巴向头部寻找公共后缀;
这样操作会容易得多。
代码
本题测试点6未通过,可能是有独立于链表的结点。
#include <iostream>
#include <vector>
using namespace std;
typedef struct ndoe_st {
int addr;
char data;
int next;
} node_st;
node_st myList[100001] = {0x0};
int main() {
int START_WORD1(0), START_WORD2(0), N(0);
cin >> START_WORD1 >> START_WORD2 >> N;
// Read list
for(int i = 0; i < N; i++) {
int _addr(0), _next(0);
char _data(0);
cin >> _addr >> _data >> _next;
myList[_addr].addr = _addr;
myList[_addr].data = _data;
myList[_addr].next = _next;
}
// Copy list to a vector
vector<node_st> Word1;
vector<node_st> Word2;
for(int i = START_WORD1; i >= 0; i = myList[i].next)
Word1.push_back( myList[i] );
for(int i = START_WORD2; i >= 0; i = myList[i].next)
Word2.push_back( myList[i] ) ;
// Walk two word vectors and find the common suffix
int i = Word1.size()-1;
int j = Word2.size()-1;
while( Word1[i].addr == Word2[j].addr && i >= 0 && j >= 0 ) {
i--;
j--;
}
if( i == Word1.size()-1 ) puts("-1");
else printf("%05d\n", Word1[i+1].addr);
return 0;
}