#include <iostream> #include <algorithm> #include <cmath> #include <cstring> #define maxn 100010 using namespace std; typedef struct Node{ char c; int next; // int flag; }N; N node[maxn]; int main() { int first1,first2,N; while(cin>>first1>>first2>>N) { for(int i=0;i<N;i++) { int add; cin>>add; cin>>node[add].c>>node[add].next; } int p1 = first1,l1=0; int p2 = first2,l2=0; int ans = -1; while(p1!=-1) { l1++; p1 = node[p1].next; } while(p2!=-1) { l2++; p2 = node[p2].next; } p1 = first1; while(l1>l2) { l1--; p1 = node[p1].next; } p2 = first2; while(l1<l2) { l2--; p2 = node[p2].next; } while(p1!=-1) { if(p1==p2) { ans = p1; break; } else { p1 = node[p1].next; p2 = node[p2].next; } } cout<<ans<<endl; } } // 64 位输出请用 printf("%lld")