1032. Sharing (25)-PAT

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.


1032. Sharing (25)-PAT_第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 (<= 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 00010
Sample Output 1:
67890
Sample Input 2:
00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1
Sample Output 2:

-1

推荐指数:※

来源:http://pat.zju.edu.cn/contests/pat-a-practise/1032

求两个链表的公共节点,先分别求出长度,二次遍历即可。

这道题http://blog.csdn.net/zhu_liangwei/article/details/9878219相同。

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N=100000;
typedef struct Node{
	int next;
	char val[2];
}Node;
int find_sharing(Node * link,int head1,int len1,int head2,int len2){//make len1>=len2
	int pre=len1-len2;
	int p=head1;
	while(pre>0){
		p=link[p].next;
		pre--;
	}
	int q=head2;
	while(p!=-1){
		if(p==q)
			return q;
		q=link[q].next;
		p=link[p].next;
	}
	return -1;
}
int main()
{
	Node *link=new Node [N];
	memset(link,0,sizeof(int)*N);
	int head1,head2,n,i;
	scanf("%d%d%d",&head1,&head2,&n);
	for(i=0;i<n;i++){
		int addr;
		char val[2];
		int add_next;
		scanf("%d%s%d",&addr,val,&add_next);
		strcpy(link[addr].val,val);
		link[addr].next=add_next;
	}
	int len1=0,len2=0;
	int p=head1;
	while(p!=-1){
		len1++;
		p=link[p].next;
	}
	p=head2;
	while(p!=-1){
		len2++;
		p=link[p].next;
	}
	int res;
	if(len1>=len2)
		res=find_sharing(link,head1,len1,head2,len2);
	else
		res=find_sharing(link,head2,len2,head1,len1);
	if(res!=-1)
		printf("%05d\n",res);
	else
		printf("-1\n");
	return 0;
}


你可能感兴趣的:(1032. Sharing (25)-PAT)