fork download
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3. using namespace std;
  4. vector<ll> arr[100001],cst[100001];
  5. int vis[100001];
  6. struct node{
  7. ll ind,val;
  8. };
  9. set<node> S;
  10. bool operator < (node a,node b){
  11. if(a.val!=b.val)return a.val<b.val;
  12. return a.ind<b.ind;
  13. }
  14. ll solve(ll x,ll y){
  15. S.insert({x,0});
  16. while(S.size()){
  17. node cur=*S.begin();
  18. S.erase(S.begin());
  19. if(vis[cur.ind]!=-1)continue;
  20. vis[cur.ind]=cur.val;
  21. if(cur.ind==y)break;
  22. for(int i=0;i<arr[cur.ind].size();i++)
  23. S.insert({arr[cur.ind][i],cst[cur.ind][i]+cur.val});
  24. }
  25. return vis[y];
  26. }
  27. int main() {
  28. int cases;cin>>cases;
  29. while(cases--){
  30. ll n,m;
  31. cin>>n>>m;
  32. for(int i=0;i<m;i++){
  33. ll x,y,z;
  34. cin>>x>>y>>z;
  35. arr[x].push_back(y);
  36. cst[x].push_back(z);
  37. arr[y].push_back(x);
  38. cst[y].push_back(z);
  39. }
  40. ll q;
  41. cin>>q;
  42. while(q--){
  43. ll x,y;
  44. cin>>x>>y;
  45. memset(vis,-1,sizeof vis);
  46. cout<<solve(x,y)<<endl;
  47. for(int i=0;i<n;i++){
  48. arr[i].clear();
  49. cst[i].clear();
  50. }
  51. }
  52. }
  53. return 0;
  54. }
Success #stdin #stdout 0s 8780KB
stdin
1
5 10
1 2 3
1 3 2
1 4 9
1 5 7
2 3 4
2 4 5
2 5 6
3 4 5
3 5 6
4 5 1
1
1 4

stdout
7