#include <bits/stdc++.h>
using namespace std;
int n;
vector<vector<pair<int,int> > > a;
vector<int> dist;
void dijkstra(int src,int dest){
priority_queue<pair<int,int>, vector<pair<int,int> >, greater<pair<int,int> > >pq;
pq.push({0,src});
while(!pq.empty()){
int u=pq.top().second;
pq.pop();
for(auto i:a[u]){
int v=i.first,cost=i.second;
if(dist[v]>dist[u]+cost){
dist[v]=dist[u]+cost;
pq.push({dist[v],v});
}
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
cin>>n;
map<string,int> map_names;
vector<string> array_names;
a.assign(n,vector<pair<int,int> >());
for(int i=0;i<n;i++){
string s;
cin>>s;
array_names.push_back(s);
int u=array_names.size()-1;
map_names[s]=u;
int e;
cin>>e;
for(int i=0;i<e;i++){
int idx,cost;
cin>>idx>>cost;
idx--;
a[u].push_back({idx,cost});
}
}
int paths;
cin>>paths;
for(int i=0;i<paths;i++){
dist.assign(n,INT_MAX);
string source,destination;
cin>>source>>destination;
dist[map_names[source]]=0;
if(source!=destination)
dijkstra(map_names[source],map_names[destination]);
cout<<dist[map_names[destination]]<<'\n';
}
}
return 0;
}
using namespace std;
int n;
vector<vector<pair<int,int> > > a;
vector<int> dist;
void dijkstra(int src,int dest){
priority_queue<pair<int,int>, vector<pair<int,int> >, greater<pair<int,int> > >pq;
pq.push({0,src});
while(!pq.empty()){
int u=pq.top().second;
pq.pop();
for(auto i:a[u]){
int v=i.first,cost=i.second;
if(dist[v]>dist[u]+cost){
dist[v]=dist[u]+cost;
pq.push({dist[v],v});
}
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
cin>>n;
map<string,int> map_names;
vector<string> array_names;
a.assign(n,vector<pair<int,int> >());
for(int i=0;i<n;i++){
string s;
cin>>s;
array_names.push_back(s);
int u=array_names.size()-1;
map_names[s]=u;
int e;
cin>>e;
for(int i=0;i<e;i++){
int idx,cost;
cin>>idx>>cost;
idx--;
a[u].push_back({idx,cost});
}
}
int paths;
cin>>paths;
for(int i=0;i<paths;i++){
dist.assign(n,INT_MAX);
string source,destination;
cin>>source>>destination;
dist[map_names[source]]=0;
if(source!=destination)
dijkstra(map_names[source],map_names[destination]);
cout<<dist[map_names[destination]]<<'\n';
}
}
return 0;
}
Comments
Post a Comment