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).
Input Specification:
Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positive N (<= 10^5^), 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.
解答:对于给定的定长地址的链表可以用vector模拟实现,例如在本题中可以用vector对象的下标来表示地址,每个元素存储下一个地址(本题中的字符因为没用,所以不需要存储,如果需要可以用结构体实现下)。因此一个字符串其实就是一个地址串,只要找相同的尾地址串就行。
#include<vector>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int addr1, addr2, N;
vector<int> links(100010);
vector<int> addlink1, addlink2;
scanf("%d %d %d", &addr1, &addr2, &N);
while(N--){
int addr, nxt;
char ch;
scanf("%d %c %d", &addr, &ch, &nxt);
links[addr] = nxt;
}
while(addr1 != -1){
addlink1.push_back(addr1);
addr1 = links[addr1];
}
addlink1.push_back(-1);
while(addr2 != -1){
addlink2.push_back(addr2);
addr2 = links[addr2];
}
addlink2.push_back(-1);
//找到第一个相同的address
reverse(addlink1.begin(), addlink1.end());
reverse(addlink2.begin(), addlink2.end());
int same = -1;
for(int i = 1; i < addlink1.size() && i < addlink2.size(); ++i){
if(addlink1[i] == addlink2[i]){
same = addlink1[i];
}else{
break;
}
}
if(same == -1) printf("-1\n");
else printf("%05d\n", same);
return 0;
}