#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <assert.h>

using namespace std;

int parse_time(string str)
{
	string h, m, s;
	h = str.substr(0, 2);
	m = str.substr(3, 2);
	s = str.substr(6, 2);
	int time = atoi(h.c_str())*3600 + atoi(m.c_str()) * 60 + atoi(s.c_str());
	return time;
}

struct flight
{
	string name;
	int dep, arr, cost;
	flight():name(""), dep(0), arr(0), cost(0) {};
	flight(string n, string s1, string s2, int c): name(n), dep(parse_time(s1)), arr(parse_time(s2)), cost(c) {};
};

const int dif = 15*60;


int main()
{
	freopen("flight.in", "r", stdin);
	freopen("flight.out", "w", stdout);
	int n;
	cin >> n;
	vector<flight> a(n);
	for (int i = 0; i < n; i++)
	{
		string s, s1, s2; int t;
		cin >> s >> s1 >> s2 >> t;
		a[i] = flight(s, s1, s2, t);
	}
	int m;
	cin >> m;
	vector<flight> b(m);
	for (int i = 0; i < m; i++)
	{
		string s, s1, s2; int t;
		cin >> s >> s1 >> s2 >> t;
		b[i] = flight(s, s1, s2, t);
	}
	pair<int, int> ans = make_pair(2e9, 2e9);
	pair<string, string> ans2;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			if (a[i].arr + dif <= b[j].dep)
			{
				pair<int, int> tmp = make_pair(a[i].cost + b[j].cost, b[j].dep);
				if (tmp < ans)
				{
					ans = tmp;
					ans2 = make_pair(a[i].name, b[j].name);
				}
			}
	cout << ans2.first << "\n";
	cout << ans2.second << "\n";
}