题目描述:
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).
输入描述:
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.
输出描述:
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.(题目转自牛客网)
===================================================================================================================
意译:题目给我们两个字符串,为了节省空间,两个字符串有可能后面有交汇的结点,比如:being与playing可以公用ing来节省空间,而结点i就是他 们的第一个交汇结点,现在给我们不超过10万个结点,共可以组成两个字符串,每个结点有下一个结点的地址,与本结点代表字母与本结点地址 的信息。要求我们找出两个字符串中第一个交汇的结点的地址并显示。
输入描述:
第一个串头的地址 第二个串头的地址 结点个数N
第一个结点地址 第一个结点内含字母 相对于第一个结点所在串中位置的下一位置的结点
第二个结点地址 第二个结点内含字母 相对于第二个结点所在串中位置的下一位置的结点
。。。。。。
第N个结点地址 第N个结点内含字母 相对于第N个结点所在串中位置的下一位置的结点
输出描述:
若有交汇结点则输出第一个交汇的结点的地址,若无则输出-1
====================================================================================================================================
#include<iostream>
#include<vector>
using namespace std;
typedef struct node{
char data;
int Next_Addr; //下一个结点地址
int flag; //访问次数标记
}Node;
int Get_Com(vector<Node> &Pre, int h1, int h2){
int i,t1,t2;
i = h1;
while(i != -1){
Pre[i].flag += 1;
i = Pre[i].Next_Addr; //访问串1的下一个结点
}
i = h2;
while(i != -1){
Pre[i].flag += 1;
if(Pre[i].flag == 2)
return i;
i = Pre[i].Next_Addr;
}
return -1; //说明所有结点都只有被访问过一次,即无交汇结点,返回-1
}
int main(){
int N,Addr1,Addr2,temp_Addr;
int Com;
vector<Node> Pre;
while(cin>>Addr1>>Addr2>>N){
Pre.clear();
Pre.resize(100000);
for(int i=0; i<N; i++)
Pre[i].flag = 0;
for(int i=0; i<N; i++){
cin>>temp_Addr;
cin>>Pre[temp_Addr].data>>Pre[temp_Addr].Next_Addr;
}
Com = Get_Com(Pre,Addr1,Addr2);
if(Com != -1){ //-1前面不需要补充0
cout.width(5);
cout.fill('0');
}
cout<<Com<<endl;
}
return 0;
}