#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <cstring>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>

#define FOR(i,b,n) for(int i=b;i<n;i++)
#define RFOR(i,b,n) for(int i=n-1;i>=b;i--)
#define CLR(mat) memset(mat, 0, sizeof(mat))
#define NCLR(mat) memset(mat, -1, sizeof(mat))

using namespace std;

static const double EPS = 1e-9;
typedef long long ll;
typedef pair<int, int> paii;

int am[2][500][500] = {0};
int ms[2][500][500] = {0};

int n, m, r;

int solve()
{
	FOR(k, 0, 2)
		FOR(j,0,m+1)
			FOR(i,0,m+1)
			{
				if( am[k][j][i] == 0)
					ms[k][j][i] = 3000;
				else
					ms[k][j][i] = am[k][j][i];
			}
	
	FOR(t, 0, 2)
		FOR(k, 1, m+1)
			FOR(j, 1, m+1)
				FOR(i, 1, m+1)
				{
					ms[t][j][i] = min(ms[t][j][i], ms[t][j][k] + ms[t][k][i]);
				}
				
	return 0;
}

int main()
{
	while(cin >> n >> m, (n||m))
	{
		CLR(am);
		CLR(ms);
		
		FOR(i,0,n)
		{
			int a, b, c, t;
			cin >> a >> b >> c >> t;
			
			am[0][a][b] = c;
			am[1][a][b] = t;
		}
		
		solve();
		
		cin >> r;
		
		FOR(i,0,r)
		{
			int a, b, t;
			cin >> a >> b >> t;
			cout << ms[t][a][b] << endl;
		}
	}
	
	return 0;
}