A1032 Sharing

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.

Figure1

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

Code:

#pragma warning(disable: 4996)
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Node {
char word;
int next;
}node[100001];

int main(int argc, char* argv[]) {
//读初始值→将数据存为静态链表→根据静态链表得到两个字符串→从后往前对比字符串找到suffix
int add_1, add_2, N;
cin >> add_1 >> add_2 >> N;

int pos, next;
char word;
for (int i = 0; i < N; i++) {
cin >> pos >> word >> next;
node[pos].word = word;
node[pos].next = next;
}

vector<char> words_1, words_2;
vector<int> pos_1, pos_2;//地址没存下来,找到这个字母之外还需要找到这个字母的位置
while (add_1 != -1) {
words_1.push_back(node[add_1].word);
pos_1.push_back(add_1);
add_1 = node[add_1].next;
}
while (add_2 != -1) {
words_2.push_back(node[add_2].word);
pos_2.push_back(add_2);
add_2 = node[add_2].next;
}

int index = -1;
for (int i = 1; i <= min(words_1.size(), words_2.size()); i++) {
if (words_1[words_1.size() - i] == words_2[words_2.size() - i] && pos_1[pos_1.size() - i] == pos_2[pos_2.size() - i])
index = pos_1[words_1.size() - i];
else break;
}

if (index != -1)
printf("%05d", index);//30分钟解决,还没debug,下去买个夜宵,2021-04-02,欧耶我又开始刷题了
else
cout << index;
system("pause");
return 0;
}
//3次调通,但最后两个检查点错了,拿到了20分。
//想的时间要和写五五开,找测试点的努力有时大于写代码。
//检查点4——要注意输出的是地址!!!要用%05d补0;检查点5——巨大的坑...后缀相同的条件是,必须字母和“地址”都是一样的!!!!!我真是服了,https://blog.csdn.net/weixin_41359213/article/details/107477558

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×