#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define int long long
#define faster() ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
// do phuc tap (V^3) => ap dung cho V <= 400
int Mat[1005][1005] , n , m ;
void Floyd(){
for(int k = 1 ; k <= n ; k++){
for(int i = 1 ; i <= n ; i++){
for(int j = 1 ; j <= n ; j++){
Mat[i][j] = min(Mat[i][j] , Mat[i][k] + Mat[k][j]);
}
}
}
}
void solve(){
cin >> n >> m ;
for(int i = 1 ; i <= n ; i++){
for(int j = 1 ; j <= m ; j++){
if( i == j) Mat[i][j] = 0 ;
else Mat[i][j] = 1e9 ;
}
}
for(int i = 1 ; i <= m ; i++){
int x , y, w ; cin >> x >> y >> w ;
Mat[x][y] = Mat[y][x] = w ;
}
Floyd();
int q ; cin >> q ;
while(q--){
int u , v ; cin >> u >> v ;
cout << Mat[u][v] << endl;
}
}
signed main() {
faster();
int test = 1 ;
// cin >> test ;
while(test--) solve();
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CiNkZWZpbmUgZW5kbCAiXG4iCiNkZWZpbmUgaW50IGxvbmcgbG9uZwojZGVmaW5lIGZhc3RlcigpIGlvczo6c3luY193aXRoX3N0ZGlvKGZhbHNlKTsgY2luLnRpZShudWxscHRyKTsgY291dC50aWUobnVsbHB0cik7CgovLyBkbyBwaHVjIHRhcCAoVl4zKSA9PiBhcCBkdW5nIGNobyBWIDw9IDQwMAppbnQgTWF0WzEwMDVdWzEwMDVdICwgbiAsIG0gOwp2b2lkIEZsb3lkKCl7CiAgICBmb3IoaW50IGsgPSAxIDsgayA8PSBuIDsgaysrKXsKICAgICAgICBmb3IoaW50IGkgPSAxIDsgaSA8PSBuIDsgaSsrKXsKICAgICAgICAgICAgZm9yKGludCBqID0gMSA7IGogPD0gbiA7IGorKyl7CiAgICAgICAgICAgICAgICBNYXRbaV1bal0gPSBtaW4oTWF0W2ldW2pdICwg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