题目地址:点击打开链接
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.
![](http://www.patest.cn/upload/1w_m16pjsommxz.jpg)
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
where Address 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 Input 1: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 00010Sample Output 1:
67890Sample Input 2:
00001 00002 4 00001 a 10001 10001 s -1 00002 a 10002 10002 t -1Sample Output 2:
-1题意:输入两个单词的各位字符和地址和下一位字符地址,输出公共的字符部分的第一个字符的地址。
解法:把第一个单词的每一个字符放进集合set ,把第二个单词里的字符在set里进行查找,找到了就输出这个字符的地址。
我的C++代码:
#include <iostream>
#include<set>
using namespace std;
int main()
{
int n, pointer1, pointer2 ;//n结点总个数, pointer1第一个单词首结点地址
int nodeaddress[100000]; //数组保存各结点地址
set<int>word1charset; //单词1字符组成的集合
int addr, next; //addr地址,next下一个结点地址
char ch; //结点字符信息
cin >> pointer1 >> pointer2 >> n;
for (int i = 0; i<n; i++)
{
cin >> addr >> ch >> next;
nodeaddress[addr] = next;//保存下一个结点的地址
}
while (pointer1 != -1)//当单词1字符没被遍历完
{
word1charset.insert(pointer1);//把单词1的字符添加进set
pointer1 = nodeaddress[pointer1];//地址向后移
}
while (pointer2 != -1)//当单词2字符没被遍历完
{
if (word1charset.count(pointer2) != 0)//找到了相同的元素
{
printf("%05d", pointer2);//输出相同的字符的地址
return 0; //结束退出程序
}
pointer2 = nodeaddress[pointer2];//地址向后移
}
printf("-1");
return 0;
}