N = int(1e5 + 10)
ne = [0] * N
st = [False] * N
h1,h2,n = map(int,input().split())
for i in range(n):
addr,val,next = input().split()
addr = int(addr)
next = int(next)
ne[addr] = next
i = h1
while i != -1: # 遍历第一个链表,把每个地址标记为True
st[i] = True
i = ne[i]
i = h2
while i != -1: # 遍历第二个链表
if st[i]: # 如果st[i]第一次为True,则i这个地址是两个链表共享的第一个链表单元
print(f'{i:05d}') # 不足5位前面补0
exit(0)
i = ne[i]
print(-1)