(PAT)1032 Sharing (可以用数组表示地址)

发布时间:2023-05-19 09:18:21

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,loadingandbeingare stored as showed in Figure 1.

(PAT)1032 Sharing (可以用数组表示地址)_ci

Figure 1

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

Input Specification:

Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positiveN(≤105), where the two addresses are the addresses of the first nodes of the two words, andNis the total number of nodes. The address of a node is a 5-digit positive integer, and NULL is represented by−1.

ThenNlines follow, each describes a node in the format:

Address Data Next

whereAddressis the position of the node,Datais the letter contained by this node which is an English letter chosen from { a-z, A-Z }, andNextis 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-1instead.

Sample Input 1:

11111 22222 967890 i 0000200010 a 1234500003 g -112345 D 6789000002 n 0000322222 B 2345611111 L 0000123456 e 6789000001 o 00010

Sample Output 1:


Sample Input 2:

00001 00002 400001 a 1000110001 s -100002 a 1000210002 t -1

Sample Output 2:





#include <iostream>#include <algorithm>using namespace std;const int maxn = 100010;  ///地址池classs Node {public:int next;char algpa;bool flag;}node[maxn];int main() {for (int i = 0; i < maxn; ++i) {node[i].flag = false;}int firstAddr = 0;int secondAddr = 0;int n = 0;cin >> firstAddr >> secondAddr >> n;for (int i = 0; i < n; ++i) {int addr,next = 0;char data;cin >> addr >> data >> next;node[addr].next = next;node[addr].algpa = data; }int p1 = firstAddr;  ///int第一个首个地址 p2 = secondAddr; //第二个首地址while (p1 != -1) {  ///首先标记node[p1]的第一个链表.flag = true;p1 = node[p1].next;   ///向下遍历}while (p2 != -1) {if (node[p2].flag == true) {  ///找到第一个重合词break;}p2 = node[p2].next;}if (p2 != -1) {if (node[p2].flag == true) {  ///找到第一个重合词break;}p2 = node[p2].next;}if (p2 != -1) {printf("%05d\n", p2);}else {printf("-1\n");}return 0;}

ps 图灵课堂老师从近一百套最新一线互联网公司面试题中精选而出,涵盖Java架构面试 所有技术栈,包括JVM,Mysql,并发,Spring,Redis,MQ,Zookeeper,Netty, Dubbo,Spring Boot,Spring Cloud,数据结构与算法,设计模式等相关技术领域的大 厂面试题及详解。 详情咨询客服获取全套面经试题。

上一篇 matlab zeros和ones
下一篇 (PAT 1101)Quick Sort (递推法)