#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <algorithm>
using namespace std;

const int INF = 1 << 30;
const int V = 100000;
const int E = 500000;
struct Edge{ int to, cost; };
vector<Edge> list[E];
typedef pair<int, int> P;
int d[V];

int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	
	int v, e, r;
	cin >> v >> e >> r;
	
	int a, b, c;
	for(int i = 0; i < e; ++i){
		cin >> a >> b >> c;
		list[a].push_back(Edge{b, c});
	}
	
	priority_queue<P, vector<P>, greater<P>> pque;
	pque.push(P(0, r));
	fill(d, d + v, INF);
	d[r] = 0;
	
	while(!pque.empty()){
		P p = pque.top();
		pque.pop();
		int v1 = p.second;
		if(d[v1] < p.first) continue;
		
		for(int i = 0; i < list[v1].size(); ++i){
			Edge e1 = list[v1][i];
			if(d[e1.to] > d[v1] + e1.cost){
				d[e1.to] = d[v1] + e1.cost;
				pque.push(P(d[e1.to], e1.to));
			}
		}
	}
	
	for(int i = 0; i < v; ++i){
		if(d[i] != INF)
			cout << d[i] << endl;
		else
			cout << "INF" << endl;
	}
	
	return 0;
}
#include<functional>
#include<algorithm>
#include<iostream>
#include<utility>
#include<string>
#include<vector>
#include<cmath>
#include<stack>
#include<queue>
#include<deque>
#include<map>
#define rep(i,n) for(int i=0;i<n;i++)
#define loop(i,x,n) for(int i=x;i<n;i++)
#define pf push_front
#define pb push_back
#define int long long
using namespace std;
const int INF=1000000007;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
const int N=101;

int cost[N][N];
int tim[N][N];

int bfs(int n,int p,int q,int graph[N][N]){
  vector<int> v(n);
  queue<int> que;
  rep(i,n)v[i]=INF;
  v[p]=0;
  que.push(p);
  int u;
  while(!que.empty()){
    u=que.front(),que.pop();
   
    rep(i,n){
      if(v[i]>v[u]+graph[u][i]){
        v[i]=v[u]+graph[u][i];
        que.push(i);
      }
    }
  }
  return v[q];
}


signed main(){
  int n,m;
  while(cin>>n>>m,n!=0){ 
    rep(i,m)rep(j,m){
      cost[i][j]=(i==j?0:INF);
      tim[i][j]=(i==j?0:INF);
    }
    rep(i,n){
      int a,b,c,t;
      cin>>a>>b>>c>>t;
      a--;b--;
      cost[a][b]=cost[b][a]=c;
      tim[a][b]=tim[b][a]=t;
    }
    int k;
    cin>>k;
    rep(i,k){
      int p,q,r;
      cin>>p>>q>>r;
      p--;q--;
      int ans;
      if(r==0){
        ans=bfs(m,p,q,cost);
      }else{
        ans=bfs(m,p,q,tim);
      }
      cout<<ans<<endl;
    }
  }
  return 0;
}