#include <iostream>
#include <string>

using namespace std;

void process_command(istream &istr, string &str);
void my_print(const string &str, int a, int b);
void my_reverse(string &str, int a, int b);
void my_replace(string &str, int a, int b, string &p);


int main(){
    string str;
    cin >> str;
    int q;
    cin >> q;
    for(int i = 0; i != q; ++i){
        process_command(cin, str);
    }
}

void process_command(istream &istr, string &str){
    string command;
    istr >> command;
    if (command == "print"){
        int a, b;
        istr >> a >> b;
        my_print(str, a, b);
    }else if (command == "reverse"){
        int a, b;
        istr >> a >> b;
        my_reverse(str, a, b);
    }else if (command == "replace"){
        int a, b;
        string p;
        istr >> a >> b >> p;
        my_replace(str, a, b, p);
    }else {
        cout << "Unexpected command encountered! " << command << endl;
    }

}
void my_print(const string &str, int a, int b){
    cout << str.substr(a, b - a + 1) << endl;
}

void my_reverse(string &str, int a, int b){
    while(a < b){
        auto tmp = str[a];
        str[a] = str[b];
        str[b] = tmp;
        ++a;
        --b;
    }
}

void my_replace(string &str, int a, int b, string &p){
    str.replace(a, b - a + 1, p);
}
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<vector>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<time.h>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
const double PI=acos(-1);
const double EPS=1e-10;
const int inf=1e8;
using namespace std;
typedef long long ll;
typedef vector<int> vi;
vector<vector<char> >tmp;
vector<vector<int> >scr;
int main(){
	int n,m;
	while(cin>>n>>m,n||m){
		vector<int>d(m);
		vector<vi >cost(m,vector<int>(m));
		vector<vi >tim(m,vector<int>(m));
		vector<bool>used(m);
		rep(i,m)rep(j,m){cost[i][j]=inf;tim[i][j]=inf;}
		rep(i,n){
			int a,b,c,d;
			cin>>a>>b>>c>>d;
			a--;b--;
			cost[a][b]=cost[b][a]=c;
			tim[a][b]=tim[b][a]=d;
		}
		cin>>n;
		rep(i,n){
			int a,b,c;
			cin>>a>>b>>c;
			a--;b--;
			rep(j,m)d[j]=inf;
			rep(j,m)used[j]=false;
			if(c){
				d[a]=0;
				while(1){
					int v=-1;
					rep(j,m)if(!used[j]&&(v==-1||d[v]>d[j]))v=j;
					if(v==-1)break;
					used[v]=true;
					rep(j,m)d[j]=min(d[j],d[v]+tim[v][j]);
				}
			}else{
				d[a]=0;
				while(1){
					int v=-1;
					rep(j,m)if(!used[j]&&(v==-1||d[v]>d[j]))v=j;
					if(v==-1)break;
					used[v]=true;
					rep(j,m)d[j]=min(d[j],d[v]+cost[v][j]);
				}
			}
			cout<<d[b]<<endl;
		}
	}
}