#include <bits/stdc++.h>

using namespace std;

int main()
{

    int testcases;
    cin >> testcases;
    while(testcases-->0)
    {
        int cities;
        cin >> cities;
        string arr[cities+1];
        vector<pair<int,int>> adjacencylist[cities+1]; // --->> see +1 added
        unordered_map<string,int> mymap;
        for(int i=1;i<=cities;i++)
        {
            cin >> arr[i];
            mymap[arr[i]]=i;
            int temp;
            cin >> temp;
            while(temp-->0)
            {
                int nr,cost;
                cin >> nr >> cost;
                adjacencylist[i].push_back(pair<int,int>(cost,nr));  // -->> crash , because i==cities, but adjacencylist doesnot have cities index.
            }
        }
        int xx;
        cin >> xx;
        while(xx-->0)
        {
            string source,destination;
        cin >>  source >> destination;
        int index1=mymap[source],index2=mymap[destination];
        int dist[cities+1];
        for(int i=1;i<=cities;i++)
        {
            dist[i]=10000;
        }
        dist[index1]=0;
        priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> myqueue;
        myqueue.push(pair<int,int>(dist[index1],index1));
        while(myqueue.size())
        {
            pair<int,int> p=myqueue.top();
            myqueue.pop();
            //cout << "extracted min " << p.second << " ans distance of it is " << p.first << endl;
            
            //---->> see need check valid or not p element
            if (dist[p.second] != p.first )
                continue;
            //------------------------------------------------
            for(pair<int,int> vv : adjacencylist[p.second])
            {
                if(dist[vv.second]>dist[p.second]+vv.first)
                {
                    dist[vv.second]=p.first+vv.first;
                   // cout << "pushing " << vv.second << " vertex ans its distance is " << dist[vv.second] << endl;
                    myqueue.push(pair<int,int>(dist[vv.second],vv.second));
                }
            }
        }
        cout << dist[index2] << endl;
        }
        
    }
}
