#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <sstream>
#include <list>
#include <climits>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <ctime>
#include <math.h>
#include <cstring>
#include <iomanip>
using namespace std;
typedef long long ll;
const ll N = 10000;
string s1, s2;
typedef struct edge
{
ll f, t, w;
} edge;
vector<edge> e[N];
ll dis[N];
typedef struct node
{
ll id;
ll step;
bool operator<(const node &a) const
{
return this->step > a.step;
}
} node;
unordered_map<string, ll> table;
void bfs(ll x)
{
for (int i = 0; i < N; i++)
{
dis[i] = 0x3f3f3f3f3f3f3f3f;
}
dis[x] = 0;
priority_queue<node> q;
q.push({x, 0});
while (!q.empty())
{
node now = q.top();
q.pop();
if (now.id == table[s2])
{
break;
}
for (int i = 0; i < e[now.id].size(); i++)
{
ll tid = e[now.id][i].t;
ll tstep = e[now.id][i].w;
if (dis[tid] > now.step + tstep)
{
q.push({tid, tstep});
dis[tid] = tstep + now.step;
}
}
}
if (dis[table[s2]] == 0x3f3f3f3f3f3f3f3f)
{
cout << "Roger" << endl;
}
else
{
cout << dis[table[s2]] << endl;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
ll n, m;
cin >> n >> m;
for (ll i = 1; i <= m; i++)
{
string x, y;
ll t;
cin >> x >> y >> t;
if (table.count(x) == 0)
table[x] = table.size() + 1;
if (table.count(y) == 0)
table[y] = table.size() + 1;
e[table[x]].push_back({table[x], table[y], t});
}
ll T;
cin >> T;
while (T--)
{
cin >> s1 >> s2;
bfs(table[s1]);
}
return 0;
}