PAT 1032 Sharing

http://pat.zju.edu.cn/contests/pat-practise/1032

好吧,注意有可能存在空串,别的就没什么了,代码写的比较烂,有好多不必要的重复。

 1 #include <stdio.h>
 2 struct Node{
 3     int next_num;
 4     char ch;
 5 };
 6 
 7 struct Node nodes[100002];
 8 int main()
 9 {
10     int head1,head2,node_num;
11     scanf("%d%d%d",&head1,&head2,&node_num);
12     int i;
13     for(i=0;i<node_num;i++) {
14         int cur_node,next_num;
15         char cur_ch;
16         scanf("%d %c %d",&cur_node,&cur_ch,&next_num);
17         nodes[cur_node].ch=cur_ch;
18         nodes[cur_node].next_num=next_num;
19     }
20 
21     if(head1==-1||head2==-1){
22         printf("-1\n");
23         return 0;
24     }
25     int len1=0,len2=0;
26 
27     int nu=head1;
28     while(nodes[nu].next_num!=-1) {
29         nu=nodes[nu].next_num;
30         len1++;
31     }
32     nu=head2;
33     while(nodes[nu].next_num!=-1) {
34         nu=nodes[nu].next_num;
35         len2++;
36     }
37 
38     int max=-1;
39     if(len1!=len2) {
40         if(len1>len2) {
41             max=len1;
42         } else {
43             max=len2;
44         }
45     }
46 
47     if(max==len1) {
48         int dif=len1-len2;
49         while(dif--) {
50             head1=nodes[head1].next_num;
51         }
52     } else {
53         int dif=len2-len1;
54         while(dif--) {
55             head2=nodes[head2].next_num;
56         }
57     }
58     //now aligned
59 
60     while(head1!=-1&&head2!=-1) {
61         if(head1==head2) {
62             printf("%05d\n",head1);
63             return 0;
64         }
65         head1=nodes[head1].next_num;
66         head2=nodes[head2].next_num;
67     }
68     printf("-1\n");
69     return 0;
70 }
原文地址:https://www.cnblogs.com/yangce/p/2546756.html