#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 60; const ll INF = 0x3f3f3f3f3f3f3f3f; ll e[maxn][maxn], fa[110][maxn][maxn], fb[210][maxn][maxn]; int n, m, q; int s, t, k; void mul(ll a[][maxn], ll b[][maxn], ll c[][maxn]){ ll ans[maxn][maxn]; memset(ans, 0x3f, sizeof(ans)); for(int i=1; i<=n; i++){ for(int j=1; j<=n; j++){ for(int k=1; k<=n; k++){ ans[i][j] = min(ans[i][j], a[i][k]+b[k][j]); } } } memcpy(c, ans, sizeof(ans)); } void init(){ memcpy(fb[1], e, sizeof(e)); for(int i=2; i<=200; i++){ mul(e, fb[i-1], fb[i]); } memcpy(fa[1], fb[100], sizeof(e)); for(int i=2; i<=100; i++){ mul(fb[100], fa[i-1], fa[i]); } for(int k=200-1; k>=1; k--){ for(int i=1; i<=100; i++){ for(int j=1; j<=100; j++){ fb[k][i][j] = min(fb[k][i][j], fb[k+1][i][j]); } } } } ll query(int s, int t, int a, int b){ ll ans = INF; for(int i=1; i<=n; i++){ ans = min(fa[a][s][i]+fb[b][i][t], ans); } return ans; } int main() { int tt; scanf("%d", &tt); while(tt--){ scanf("%d%d", &n, &m); int u, v, w; memset(e, 0x3f, sizeof(e)); memset(fa, 0x3f, sizeof(fa)); memset(fb, 0x3f, sizeof(fb)); for(int i=0; i<m; i++){ scanf("%d%d%d", &u, &v, &w); e[u][v] = min(e[u][v], 1ll*w); } init(); scanf("%d", &q); ll ans; while(q--){ scanf("%d%d%d", &s, &t, &k); if(k<=100){ ans = fb[k][s][t]; if(ans == INF) printf("-1\n"); else printf("%lld\n", ans); } else{ int a, b; a = (k-1)/100, b = k-a*100; ans = query(s, t, a, b); if(ans == INF){ printf("-1\n"); } else{ printf("%lld\n", ans); } } } } return 0; }
|