建两条双向链表,然后从后向前比较
#include<stdio.h>
#define SIZE 100000
struct list{
int add;
struct list *next, *forward;
char key;
};
struct Node{
int add,next;
char key;
}node[SIZE];
int main(){
freopen("1.in", "r", stdin);
int n, starta, startb;
scanf("%d%d%d", &starta, &startb, &n);
int i;
for (i = 0; i < n; i++)
scanf("%d %c %d", &node[i].add, &node[i].key, &node[i].next);
int next;
struct list *ha,*ta;
ha = new struct list;
ha->next = NULL;
ta = ha;
next = starta;
while (next != -1){
for (i = 0; i < n;i++)
if (node[i].add == next){
struct list *nd = new struct list;
nd->add = next;
nd->key = node[i].key;
nd->next = NULL;
nd->forward = ta;
if (ta == ha)
ha->next = nd;
ta->next = nd;
ta = nd;
next = node[i].next;
}
}
struct list *hb, *tb;
hb = new struct list;
hb->next = NULL;
tb = hb;
next = startb;
while (next != -1){
for (i = 0; i < n; i++)
if (node[i].add == next){
struct list *nd = new struct list;
nd->add = next;
nd->key = node[i].key;
nd->next = NULL;
nd->forward = tb;
if (tb == hb)
hb->next = nd;
tb->next = nd;
tb = nd;
next = node[i].next;
}
}
struct list *pa, *pb;
pa = ta;
pb = tb;
while (pa != ha&&pb != hb){
if (pa->add != pb->add)
break;
pa = pa->forward;
pb = pb->forward;
}
if (pa->next)
printf("%05d\n", pa->next->add);
else printf("-1\n");
return 0;
}