PAT 1032 Sharing (25)(25 分)

本文介绍了一种使用链表存储英文单词的方法,通过共享相同后缀的子链表来节省空间。详细解析了如何寻找两个单词共用后缀的起始位置,并提供了具体的算法实现,包括输入输出规范。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值