首页 > 试题广场 >

Sharing

[编程题]Sharing
  • 热度指数:2240 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
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).

输入描述:
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.


输出描述:
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.
示例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
00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1

输出

67890
-1
头像 wbc990512
发表于 2021-01-26 22:07:43
就这道题而言,有个比较取巧的方法,本题简化了链表的构造过程,直接按照链表的结构给出了每一个结点的next指针,如果说两个单词有共同后缀的话,那么在m行的输入里面必然有2行的最后一位整数是一模一样的(比如测试样例里面的D和e两节点,next都是67890的i),直接用个hash数组存next出现了几次 展开全文
头像 cyber1026
发表于 2024-03-03 10:10:16
#include <iostream> using namespace std; struct node { char data; int next; }; int main() { // word1、word2是两个单词的首地址, addr用于输入,实际上不存 展开全文
头像 电专小胖墩
发表于 2024-02-09 17:38:39
记录两种思路:按照链表的观点,找公共结点,可以利用双指针的思想实现(a+c+b=b+c+a,其中a、b分别为两个链表前缀的长度,c为公共后缀的长度)。把链表看成有向图,公共后缀结点其实就是入度为2的结点。这里提供第二种思路的代码 // // Created by Zed on 2024/2/9. / 展开全文
头像 牛客142529159号
发表于 2023-03-18 14:04:04
#include <iostream> #include <cstring> using namespace std; const int N = 1e6; int ne[N]; int main() { int a, b, n; while(cin > 展开全文
头像 粉詹眉
发表于 2024-03-07 17:55:03
#include <iostream> using namespace std; const int N=1000000; int a[N]; int main() { int address1,address2,n; while(cin>>address 展开全文

问题信息

难度:
32条回答 3289浏览

热门推荐

通过挑战的用户

查看代码