#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<string, char> PII;
const int N = 1e5+5;
struct Node {
int next;
char c;
Node() {
next = -1;
}
} X[N];
bool flag[N];
int main() {
memset(flag, false, sizeof(flag));
int s1, s2, n;
cin >> s1 >> s2 >> n;
for(int i=0; i<n; i++) {
int tmp1, tmp2;
char tmp3;
cin >> tmp1 >> tmp3 >> tmp2;
X[tmp1].c = tmp3;
X[tmp1].next = tmp2;
}
for(int i=s1; i!=-1; i=X[i].next) {
flag[i] = true;
}
bool sign = false;
for(int i=s2; i!=-1; i=X[i].next) {
if(flag[i]) {
sign = true;
printf("%05d\n", i);
break;
}
}
if(!sign) {
printf("-1\n");
}
return 0;
}