您的位置:首页 > 其它

pat 1032. Sharing (25)

2015-03-08 10:10 381 查看
建两条双向链表,然后从后向前比较

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pat