#include<bits/stdc++.h>
#define ll long long int
#define FOR(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define REP(i,n) FOR(i,0,n)
#define REP1(i,n) FOR(i,1,n)
#define MIN(a, b) ((a)<(b)?(a):(b))
#define MAX(a, b) ((a)<(b)?(a):(b))
#define INF 10e6
using namespace std;
 /*temp*/

int main(){
    int n, m, l;
    while(cin>>m>>n,n){
        int cost[n][n],time[n][n];
        // set table
        REP(i,n){
            REP(j,n){
                cost[i][j]=time[i][j]=INF;
            }
            cost[i][i]=time[i][i]=0;
        }
        // read
        REP(i,n){
            int a,b,c,t;
            a--;
            b--;
            cost[a][b]=cost[b][a]=MIN(c,cost[a][b]);
            time[a][b]=time[b][a]=MIN(t,time[a][b]);
        }
        // Warshall???Floyd Algorithm
        REP(a,n){
            REP(b,a+1){
                REP(k,n){
                    cost[a][b]=cost[b][a]=MIN(cost[a][b],cost[a][k]+cost[k][b]);
                    time[a][b]=time[b][a]=MIN(time[a][b],time[a][k]+time[k][b]);
                }
            }
        }
        // 
        cin>>q;
        REP(i,q){
            int s,d,type;
            cin>>s>>d>>type;
            s--;
            d--;
            cout<<type==0?cost[s][d]:time[s][d]<<'\n';
        }
    }
    return 0;
}