1. 程式人生 > >PAT A1032 Sharing尋找共同字尾(用靜態連結串列)

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;
}