#include<iostream>
#include<cstdio>
#define maxn 100005
using namespace std;
struct Node{
char data;
int next;
bool inFirst;
}node[maxn];
int main(){
int head1,head2,n,address,next,p;
char data;
scanf("%d%d%d",&head1,&head2,&n);
for(int i=0;i<n;i++){
scanf("%d %c %d",&address,&data,&next);
node[address]={
data,next,false};
}
for(p=head1;p!=-1;p=node[p].next)
node[p].inFirst=true;
for(p=head2;p!=-1;p=node[p].next)
if(node[p].inFirst==true) break;
if(p==-1) cout<<"-1";
else printf("%05d",p);
return 0;
}