含泪补基础
1032 Sharing
1. 题目描述
1032 Sharing (25 分)(链表)
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.
2. 解题思路
2.1 思路一(部分案例正确):
如果重合的子序列出现,那么就有2个结点指向同一个结点(并且结点address不是-1),因此我们只需要找到被指2次的这个结点。
在输入node时,如果下一个结点没有出现过,就标记下一个结点的flag为1;出现过那么就是这个结点。
/*
1032
1032 Sharing (25 分)
节点用Node存储,
序号用node的下标表示,因此结构体中还需要定义key和next
在结构体中增加一个 int flag;
在输入node时,如果下一个结点没有出现过,就标记下一个结点的flag为1
出现过那么就是这个结点
*/
#include<iostream>
using namespace std;
// 结构体放main外面,因为结构体是类型不是变量
struct{
char key;
int next;
int flag=0;
}node[100010]; // 要大于6位,因为原数据是在99999五位内
int main()
{
int ad1, ad2, n;
cin >> ad1 >>ad2 >> n;
int id, nl;
char ch;
for(int i=0; i<n; i++)
{
cin >> id >> ch >> nl;
node[id].key = ch;
node[id].next = nl;
if(nl != -1 && node[nl].flag == 1){
printf("%05d",nl);
return 0;
}
else if(nl != -1 && node[nl].flag == 0){ // 注意nl不能是-1
node[nl].flag = 1;
}
}
// 到这里还没有return说明没有相同字符
printf("-1");
return 0;
}
运行结果:
这样写只有3个案例能通过
2.2 思路二(完全正确)
这个是网上常见的一个题解,在遍历第一个链表时,将此链表的节点的flag设置为true,在遍历第二个链表时查询节点的flag值,若发现flag为true,这此节点即为要找的共同后缀的起点。
另外,逆序过来找第一个不相同的,也是不完全正确的。
注意:
- 输出补0
- 找到共同串起点后就return
/*
1032
1032 Sharing (25 分)
节点用Node存储,
序号用node的下标表示,因此结构体中还需要定义key和next
在结构体中增加一个 bool flag
*/
#include<iostream>
using namespace std;
// 结构体放main外面,因为结构体是类型不是变量
struct{
char key;
int next;
bool flag;
}node[100010]; // 要大于6位,因为原数据是在99999五位内
int main()
{
int ad1, ad2, n;
cin >> ad1 >>ad2 >> n;
int id, nl;
char ch;
for(int i=0; i<n; i++)
{
cin >> id >> ch >> nl;
node[id] = {ch, nl, false};
}
// 标记第一个words中的node
for(int i = ad1; i!=-1; i = node[i].next){
node[i].flag = true;
}
// 遍历第二个words
for(int i = ad2; i!=-1; i=node[i].next){
if(node[i].flag){
printf("%05d",i); //注意输出需要补0,因为输入的id是int不是string
return 0; // 注意这里要 return
}
}
// 到这里还没有return说明没有相同字符
printf("-1");
return 0;
}