#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <ctime>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include <functional>
#include <fstream>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <numeric>
#include <cassert>
using namespace std;
#define rep(i, n) for (int(i) = 0; (i) < (n); (i)++)
class Timer
{
  private:
    double time_limit;
    //unsigned long long int cycle_per_sec = 2500000000; // Topcoder
    unsigned long long int cycle_per_sec = 2777777777; // AtCoder
    unsigned long long int beginCycle;
    unsigned long long int getCycle()
    {
        unsigned int low, high;
        __asm__ volatile("rdtsc"
                         : "=a"(low), "=d"(high));
        return ((unsigned long long int)low) | ((unsigned long long int)high << 32);
    }

  public:
    Timer(double time_limit) : time_limit(time_limit)
    {
        beginCycle = getCycle();
    }

    double elapsedTime()
    {

        return (double)(getCycle() - beginCycle) / cycle_per_sec;
    }
    bool isTLE()
    {
        return elapsedTime() >= time_limit;
    }
};

Timer gtimer(2.85);

int main()
{
    int m, n;
    while (cin >> m >> n && m)
    {
        int wf[2][310][310] = {};
        rep(i, 2) rep(j, 310) rep(k, 310)
            wf[i][j][k] = j == k ? 0 : 1e9;

        for (int i = 0; i < m; i++)
        {
            int a, b, c, t;
            cin >> a >> b >> c >> t;
            --a, --b;
            wf[0][a][b] = min(wf[0][a][b], c);
            wf[1][a][b] = min(wf[1][a][b], t);
        }
        rep(i, 2)
        {
            rep(j, 310) rep(k, 310) rep(l, 310)
            {
                wf[i][k][l] = min(wf[i][k][j] + wf[i][j][l], wf[i][k][l]);
            }
        }
        int Q;
        cin >> Q;
        while (Q--)
        {
            int a, b, c;
            cin >> a >> b >> c;
            --a, --b;
            cout << wf[c][a][b] << endl;
        }
    }
    std::cout.flush();
    return 0;
}