目录
1,题目描述
题目描述
输入
输出
2,思路
注意
3,代码
1,题目描述
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
题目描述
用数组模拟链表,来表示英文单词的存储方式(共享相同的后缀,可以节省存储空间),输出相同后缀的首字符的地址。
输入
- 第一行:两个单词的首字符的地址,存储的总字符数N;
- 其余N行:字符的地址,存储的内容,下一个字符的地址;
输出
- 共享后缀的首字符地址;
2,思路
- 将各个节点的信息存入int data[100001]中(只需记录下一节点的位置信息,无需记录字符内容);
- 遍历两个单词,分别将其各个字符的地址存入vector<int> word1, word2中;
- 从后向前对比word1与word2,找到第一个不同的地址,此位置的上一个地址就是最终结果;
注意
- 有可能一个单词完全是另一个单词的后缀,所以在遍历word1和word2时,注意越界问题;
3,代码
#include<iostream>
#include<vector>
using namespace std;
int main(){
//#ifdef ONLINE_JUDGE
//#else
// freopen("1.txt", "r", stdin);
//#endif
int data[100002]; //只需记录下一字符的位置即可 无需接受字符
vector<int> word1, word2;
int start1, start2, n;
cin>>start1>>start2>>n;
int index, next;
char c;
for(int i = 0; i < n; i++){
scanf("%d %c %d", &index, &c, &next); //无需接受字符(未用到)
data[index] = next;
}
index = start1;
while(index != -1){
word1.push_back(index); //记录单词1所有字符的地址
index = data[index];
}
index = start2;
while(index != -1){
word2.push_back(index); //记录单词2所有字符的地址
index = data[index];
}
int i = word1.size() - 1, j = word2.size() - 1;
while(i >= 0 && j >= 0 && word1[i] == word2[j]){ //注意:可能一个单词完全是另一个单词的后缀 小心越界
i--;j--;
}
if(i == word1.size() - 1) cout<<-1;
else printf("%05d", word1[i+1]); //i与j同步 均可作为输出依据
return 0;
}