#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=1000001;
struct Node
{
char c;
int next;
}node[maxn];
bool hashtable[maxn]={false};
int main()
{
int a,b,n;
cin>>a>>b>>n;
for (int i=0;i<n;i++)
{
int t1,t2;
char t;
scanf("%d %c %d",&t1,&t,&t2);
node[t1].c=t1;
node[t1].next=t2;
}
int i=-1;
for(i=a;i!=-1;)
{
hashtable[i]=true;
i=node[i].next;
}
for(i=b;i!=-1;)
{
if(hashtable[i]==true)
break;
i=node[i].next;
}
if(i==-1)
{
printf("-1");
}
else
{
printf("%05d",i);
}
}