#include <iostream>
#include <vector>
#include <queue>
#include <map>
using namespace std;

typedef pair<int,int> P;

const int MAX_V = 101;
const int INF = 1000000009;
struct edge { int to, cost, time; };
vector<edge> G[MAX_V];
int dist[MAX_V];

int dijkstra(int s, int t, int type) {
	fill(dist, dist+MAX_V, INF);
	dist[s] = 0;
	priority_queue<P, vector<P>, greater<P> > que;
	que.push(P(0, s));
	while(!que.empty()) {
		P n = que.top(); que.pop();
		int v = n.second;
		if(v == t) return dist[v];

		for(int i=0; i<G[v].size(); i++) {
			edge& e = G[v][i];
			if(type == 0) {
				if(dist[e.to] > dist[v] + e.cost) {
					dist[e.to] = dist[v] + e.cost;
					que.push(P(dist[e.to], e.to));
				}
			} else {
				if(dist[e.to] > dist[v] + e.time) {
					dist[e.to] = dist[v] + e.time;
					que.push(P(dist[e.to], e.to));
				}
			}
		}
	}
	return INF;
}

int M, N, K;
int a, b, c, time;
int p, q, r;


int main() {
	while(scanf("%d%d", &N, &M), N|M) {
		for(int i=0; i<MAX_V; i++) G[i].clear();

		for(int i=0; i<N; i++) {
			scanf("%d%d%d%d", &a, &b, &c, &time);
			edge e = { b, c, time };
			G[a].push_back(e);
		}

		scanf("%d", &K);
		for(int i=0; i<K; i++) {
			scanf("%d%d%d", &p, &q, &r);
			int d = dijkstra(p, q, r);
			printf("%d\n", d);
		}
	}
}