#include <iostream> #include <cstdio> #include <algorithm> #include <string> #include <cmath> #include <cstring> #include <queue> #include <set> #include <vector> #include <stack> #include <map> #include <iomanip> #define PI acos(-1.0) #define Max 100005 #define inf 1<<28 #define LL(x) (x<<1) #define RR(x) (x<<1|1) #define FOR(i,s,t) for(int i=(s);i<=(t);++i) #define ll long long #define PII pair<int,int> #define mem(a,b) memset(a,b,sizeof(a)) #define mp(a,b) make_pair(a,b) using namespace std; struct kdq { int e ,l ,next ; } ed[Max] ; int head[Max] ; bool vis[Max] ; int num = 0 ; int n , m ; int dis[Max] ; vector<PII>query[Max] ; int f[Max] ; int ans[Max] ; void add(int a, int b ,int l ) { ed[num].e = b ; ed[num].l = l ; ed[num].next = head[a] ; head[a] = num ++ ; } int find(int x) { return f[x] == x ? x : f[x] = find(f[x]) ; } void init() { mem(head , -1 ) ; mem(vis,0) ; num = 0 ; mem(dis,0) ; for (int i = 0 ; i <= n ; i ++)query[i].clear() ,f[i] = i ; } void dfs(int now ,int fa) { for (int i = head[now] ; i != -1 ; i = ed[i].next ) { int v = ed[i].e ; int l = ed[i].l ; if(v == fa) continue ; dis[v] = dis[now] + l ; dfs(v , now) ; f[v] = now ; } vis[now] = 1 ; int l = query[now].size() ; for (int i = 0 ; i < l ; i ++) if(vis[query[now][i].first]) ans[query[now][i].second] = dis[now] + dis[query[now][i].first] - 2 * dis[find(query[now][i].first)] ; } int main() { while(cin >> n >> m) { init() ; for (int i = 0 ; i < m ; i ++ ) { int a , b, c ; char d ; scanf("%d%d%d",&a,&b,&c); cin >> d; add(a,b,c) ; add(b,a,c) ; } cin >> m ; for (int i = 0 ; i < m ; i ++) { int a , b ; scanf("%d%d",&a,&b) ; query[a].push_back(mp(b,i)) ; query[b].push_back(mp(a,i)) ; } dfs(1 , 0) ; for (int i = 0 ; i <m ; i ++) printf("%d\n",ans[i]) ; } return 0; }