include<iostream>
include<string>
using namespace std;
const int maxn = 1e6 + 10;
struct node {
int next, f;
}a[maxn];
int main()
{
int head1, head2, n;
scanf("%d%d%d", &head1, &head2, &n);
for (int i = 0; i < n; i++)
{
int data,next;
char c;
scanf("%d %c %d", &data, &c, &next);
a[data].next = next;
}
int p = head1;
while (p != -1)
{
a[p].f = 1;
p = a[p].next;
}
p = head2;
while (p != -1)
{
if (a[p].f == 1)
{
printf("%05d", p);
return 0;
}
p = a[p].next;
}
printf("-1");
return 0;
}