#include <bits/stdc++.h>
using namespace std;
#define loop(i, a, n) for (lli i = (a); i < (n); ++i)
#define loopD(i, a, n) for (lli i = (a); i >= (n); --i)
#define all(c) (c).begin(), (c).end()
#define rall(c) (c).rbegin(), (c).rend()
#define sz(a) ((int)a.size())
#define YES cout << "YES" << endl;
#define NO cout << "NO" << endl;
#define endl '\n'
#define fastio std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
#define pb push_back
#define pp pop_back()
#define fi first
#define si second
#define v(a) vector<int>(a)
#define vv(a) vector<vector<int>>(a)
#define present(c, x) ((c).find(x) != (c).end())
#define set_bits __builtin_popcountll
#define MOD 1000000007
#define int long long
typedef long long lli;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<lli, lli> pll;
typedef pair<int, int> pii;
typedef unordered_map<int, int> umpi;
typedef map<int, int> mpi;
typedef vector<pii> vp;
typedef vector<lli> vll;
typedef vector<vll> vvll;
struct Flight {
string src;
string to;
int dt;
int at;
int cost;
};
int parse_time(const string& time_str) {
int hour = stoi(time_str.substr(0, 2));
int minute = stoi(time_str.substr(3, 2));
string am_pm = time_str.substr(5, 2);
if (am_pm == "Am") {
if (hour == 12) hour = 0;
} else if (am_pm == "Pm") {
if (hour != 12) hour += 12;
}
return hour * 60 + minute;
}
void solve()
{
int N;
cin >> N;
vector<Flight> fff(N);
unordered_map<string, vector<Flight>> mp;
for (int i = 0; i < N; ++i) {
string src, to, des, arrival_str;
int cost;
cin >> src >> to >> des >> arrival_str >> cost;
int dt = parse_time(des);
int at = parse_time(arrival_str);
Flight ff = {src, to, dt, at, cost};
fff[i] = ff;
mp[src].push_back(ff);
}
string src, des;
cin >> src >> des;
string edes, last;
cin >> edes >> last;
int earliest_dt = parse_time(edes);
int latest_at = parse_time(last);
typedef tuple<int, int, string> State;
priority_queue<State, vector<State>, greater<State>> pq;
for (const auto& ff : mp[src]) {
if (ff.dt >= earliest_dt) {
if (
ff.at <= latest_at) {
pq.emplace(ff.cost,
ff.at,
ff.to);
}
}
}
unordered_map<string, int> ans;
unordered_map<string, int> at;
while (!pq.empty()) {
int cost_so_far, current_at;
string current_city;
tie(cost_so_far, current_at, current_city) =
pq.top();
pq.pop();
if (ans.find(current_city) != ans.end()) {
if (cost_so_far > ans[current_city]) continue;
if (cost_so_far == ans[current_city] && current_at >= at[current_city]) continue;
}
ans[current_city] = cost_so_far;
at[current_city] = current_at;
if (current_city == des) {
cout << cost_so_far;
return ;
}
for (const auto& ff : mp[current_city]) {
if (ff.dt >= current_at) {
if (ff.dt >= earliest_dt &&
ff.at <= latest_at) {
int new_cost = cost_so_far + ff.cost;
pq.emplace(new_cost,
ff.at,
ff.to);
}
}
}
}
cout << "Impossible";
return ;
}
int32_t main()
{
int tc = 1;
// cin >> tc;
while (tc--)
{
solve();
}
return 0;
}