#include<iostream>
#include<string>
#include<map>
using namespace std;
#define N 100010
typedef struct node
{
string data;
int nextad;
bool flag;
}Node;
map<int, Node> S;
Node NS[100010];
class Word
{
public:
int firstad;
string word;
int l;
};
int Find(Word &W);
int main()
{
Word A, B;
int n;
cin >> A.firstad >> B.firstad >> n;
/*for (int i = 0; i < n; i++)
{
int ad, nextad;
string d;
cin >> ad >> d >> nextad;
S[ad] = { d,nextad,false };
}*/
for (int i = 0; i < n; i++)
{
int ad, nextad;
string d;
cin >> ad >> d >> nextad;
NS[ad] = { d,nextad,false };
}
Find(A);
int ans = Find(B);
if (ans == -1)
cout << -1 << endl;
else
printf("%05d\n", ans);
//cout << A.word << endl << B.word << endl;
system("pause");
return 0;
}
int Find(Word &W)
{
int addr;
addr = W.firstad;
while (addr != -1)
{
if (NS[addr].flag)
return addr;
else
NS[addr].flag = true;
addr = NS[addr].nextad;
}
return -1;
}