#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct NODE {
bool flag;
char data;
int next;
}node[100000];
int main() {
int first,second,n,res,a,c;
char b;
cin>>first>>second>>n;
for(int i=0;i<n;i++){
cin>>a>>b>>c;
node[a]={false,b,c};
}
for(int i=first;i!=-1;i=node[i].next){
node[i].flag=true;
}
for(int i=second;i!=-1;i=node[i].next){
if(node[i].flag==true){
printf("%05d",i);
system("pause");
return 0;
}
}
printf("-1");
system("pause");
return 0;
}
06-06
1998