(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:

67890

Sample Input 2:

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

Sample Output 2:

-1

解题思路:

我们可以将数组大小定义为100010,从而形成一个地址池。根据标题中给出的地址和next地址,我们可以使用该地址池进行存储。在寻找第一个公共节点时,我们可以让链表1首先进行遍历,并标记遍历节点的位置

然后让链表2遍历,第一个公共节点是遍历到true的节点

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

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

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题