PAT A1032 Sharing寻找共同后缀(用静态链表)

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.

fig.jpg

Figure 1

You are supposed to find the starting position of the common suffix (e.g. the position of i in Figure 1).

存储英语单词的一个方法是用链表一个单词一个单词的存储,为了节约一些空间,我们可以让有相同后缀的单词共享相同的子链表,比如loading和being如图1一样存储。你需要找到共同后缀开始的位置(比如,在图1中i的位置) 

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

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.

 每个输入文件包含一个测试用例。对于每种情况,第一行包含两个节点地址和一个正数N(≤10^5),其中两个地址是两个单词的第一个节点地址,N是节点总数。节点的地址是5位正整数,空值用−1表示。随后跟着N行,每一行都描述了一个节点信息,格式如下。

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.

对于每种情况,只需输出公共后缀的5位起始位置。如果这两个单词没有公共后缀,则输出-1。

#include<cstdio>
#include<cstring>
const int maxn = 100010;
struct NODE{
	char data;//数据域 
	int next;//指针域 
	bool flag;//结点是否在第一条链表中出现
}node[maxn];

int main(){
	//初始化 
	for(int i=0;i<maxn;i++){
		node[i].flag=false;
	}
	int s1,s2,n;//s1,s2分别代表两条链表的首地址
	scanf("%d %d %d",&s1,&s2,&n);
	
	int address,next; //结点地址与后继结点地址
	char data;
	for(int i=0;i<n;i++){
		scanf("%d %c %d",&address,&data,&next);
		node[address].data=data;
		node[address].next=next;
	} 
	
	int p;
	for(p=s1;p!=-1;p=node[p].next){
		node[p].flag=true;//枚举第一条链表的所有结点 
	}
	for(p=s2;p!=-1;p=node[p].next){
		if(node[p].flag==true) break;
	} 
	if(p!=-1){//如果第二条链表还没到达结尾,说明找到了公用结点 
		printf("%05d\n",p);
	}else{
		printf("-1\n");
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/85472447