题目链接
题目分析
解题思路
思路(一): 寻找被指向过两次的那个结点即可
无法解决有无效结点的问题。有一个测试点答案错误。
思路(二):
把两个链表都扫描一遍即可!
AC程序(C++)(思路二)
/**************************
*@Author: 3stone
*@ACM: PAT. A1032 Sharing
*@Time: 18/7/16
*@IDE: VSCode 2018
***************************/
#include<cstdio>
#include<cstring>
using namespace std;
#define maxSize 100005
bool flag[maxSize];
struct Node{
int st, ed;
char c;
}node[maxSize];
int main() {
int a_start, b_start, temp_s, temp_t, n;
int key;
char temp_c;
while(scanf("%d%d%d", &a_start, &b_start, &n) != EOF) {
memset(flag, false, sizeof(flag));
key = -1;
for(int i = 0; i < n; i++) {
scanf("%d %c %d", &temp_s, &temp_c, &temp_t); //输入注意, %c前加空格
node[temp_s].st = temp_s;
node[temp_s].c = temp_c;
node[temp_s].ed = temp_t;
}
while(a_start != -1){
flag[node[a_start].st] = true;
a_start = node[a_start].ed;
}
while(b_start != -1){
if(flag[b_start])
break;
b_start = node[b_start].ed;
}
if(b_start == -1)
printf("-1\n");
else
printf("%05d\n", b_start);
}//while
return 0;
}//main
(思路一)
(一个测试点过不了)
#include<cstdio>
#include<cstring>
using namespace std;
#define maxSize 100005
bool flag[maxSize];
int main() {
int a_start, b_start, temp_s, temp_t, n;
int key;
char temp_c;
while(scanf("%d%d%d", &a_start, &b_start, &n) != EOF) {
//两者是同一个单词
if(a_start == b_start){
printf("%05d\n", a_start);
break;
}
memset(flag, false, sizeof(flag));
key = -1;
flag[a_start] = true; //防止一个单词是另一个单词的后缀
flag[b_start] = true;
for(int i = 0; i < n; i++) {
scanf("%d %c %d", &temp_s, &temp_c, &temp_t);
if(flag[temp_t])
key = temp_t;
flag[temp_t] = true;
}
if(key == -1)
printf("-1\n");
else
printf("%05d\n", key);
}
return 0;
}