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.
Figure 1
You are supposed to find the starting position of the common suffix (e.g. the position of i
in Figure 1).
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.
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.
- 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
67890
- 00001 00002 4
- 00001 a 10001
- 10001 s -1
- 00002 a 10002
- 10002 t -1
-1
首先看到这类题第一反应是定义一个结构体存放每个字母的信息,为了不受整数的各种影响,直接全部用字符串处理。
基本思路是首先存放所有字母节点,然后遍历分别找出两个单词的首字母位置,然后定义createWord函数找该单词所有下一个字母位置组成序列。
两个单词全部找到后,从后往前比较找相同的字母,记录最后一次相同字母的位置输出,找不到就输出“-1”。这里为了方便判断两个单词即两个结构体变量是否相同,对==运算符进行函数重载。
- #include
- using namespace std;
- struct node {
- //Address Data Next
- string address, data, next;
- friend bool operator==(const node& a, const node& b) {
- return (a.address == b.address && a.data == b.data && a.next == b.next);
- }
- };
- string w1, w2;
- int n;
- vector
nodelist; - vector
word1, word2; - map
wordAddr; - vector
creatWord(node w) - {
- vector
word; - node newNode = w;
- while (newNode.address!="-1") {
- word.push_back(newNode);
- newNode = wordAddr[newNode.next];
- }
- return word;
- }
- int main()
- {
- //先存储每个字母
- cin >> w1 >> w2 >> n;
- nodelist.resize(n);
- for (int i = 0; i < n; i++)
- {
- cin >> nodelist[i].address >> nodelist[i].data >> nodelist[i].next;
- wordAddr[nodelist[i].address] = nodelist[i];
- }
- wordAddr["-1"] = { "-1","-1" ,"-1" };
- //找出两个单词的首字母位置,然后找两个单词相同的的下一个字母位置
- //转换成将两个单词的所有下一个字母组成数组,然后从后往前比较找相同的
- int cnt = 0;
- for (int i = 0; i < n; i++)
- {
- if (cnt == 2)break;
- if (nodelist[i].address == w1) {
- cnt++;
- word1 = creatWord(nodelist[i]);
- }
- if (nodelist[i].address == w2) {
- cnt++;
- word2 = creatWord(nodelist[i]);
- }
- }
- //输出两个单词的相同后缀
- int len1 = word1.size();
- int len2 = word2.size();
- string res="-1";
- while (len1 != 0 && len2 != 0)
- {
- if (word1[len1 - 1] == word2[len2 - 1]) {
- res = word1[len1 - 1].address;
- len1--;
- len2--;
- }
- else break;
- }
- cout << res << endl;
- return 0;
- }