To find the first common node on the two link list;
// 题目1468:Sharing.cpp: 主项目文件。 //#include "stdafx.h" #include <cstdio> #include <algorithm> using namespace std; const int N=100003; typedef struct Node { int add,next; }Node; Node node[N]; Node list1[N],list2[N]; int n; bool cmp(Node m1, Node m2) { return m1.add<m2.add; } int findNext(int nextAdd, int start, int end) { if(start>end) return -1; int mid=(start+end)/2; if(nextAdd==node[mid].add) return mid; else if(nextAdd>node[mid].add) { start=mid+1; return findNext(nextAdd, start, end); } else { end=mid-1; return findNext(nextAdd, start, end); } } int copy(int head,Node *list) { int cur=findNext(head, 0, n-1); int length=0; while(cur!=-1) { list[length].add=node[cur].add; //list[length].ch=node[cur].ch; list[length++].next=node[cur].next; cur=findNext(node[cur].next, 0, n-1); } return length; } int sharing(int first, int second) { int length1=copy(first,list1); int length2=copy(second,list2); int start1,start2,len; if(length1>length2) start1=length1-length2,start2=0,len=length2; else start2=length2-length1,start1=0,len=length1; for(int i=0;i<len;i++) { if(list1[start1+i].add==list2[start2+i].add) return list1[start1+i].add; } return -1; } int main() { int first,second; char ch; while(scanf("%d%d%d",&first,&second,&n)==3) { for(int i=0;i<n;i++) scanf("%d%*c%c%d",&node[i].add,&ch,&node[i].next); sort(node,node+n,cmp); int res=sharing(first,second); if(res!=-1) printf("%05d\n",res); else printf("-1\n"); } return 0; }