注意到 m - n <= 20, 这意味着我们可以先dfs出一棵树,然后对于这m-n+1条边特殊考虑
我们发现,m-n+1条边最多40个点,那么我们对于这40个点暴力跑以它们为原点的最短路
查询时两个点的最短路要么在树上,要么经过这些特殊点,我们枚举这些特殊点就可以了
#include<bits/stdc++.h>
#define N 200050
using namespace std;
typedef long long ll;
const ll inf = 10000000000000000;
int n, m, q, f[N], a[N], cnt;
int find(int x){ return x == f[x] ? x : f[x] = find(f[x]);}
struct Node{
int first[N], nxt[N], to[N], w[N], tot;
void add(int x, int y, int z){
nxt[++tot] = first[x], first[x] = tot;
to[tot] = y, w[tot] = z;
}
}A, B;
int dep[N], fa[N][20]; ll d[N];
ll dis[50][N]; bool vis[N];
void dfs(int u, int f){
for(int i=1; i<=18; i++)
fa[u][i] = fa[fa[u][i-1]][i-1];
for(int i=B.first[u];i;i=B.nxt[i]){
int t = B.to[i]; if(t == f) continue;
dep[t] = dep[u] + 1; fa[t][0] = u;
d[t] = d[u] + (ll)B.w[i]; dfs(t, u);
}
}
int lca(int x, int y){
if(dep[x] < dep[y]) swap(x, y);
for(int i=18; i>=0; i--)
if(dep[fa[x][i]] >= dep[y]) x = fa[x][i];
if(x == y) return x;
for(int i=18; i>=0; i--)
if(fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
return fa[x][0];
}
#define mp make_pair
void dijsktra(int u){
priority_queue<pair<ll, int> >q; q.push(mp(0, a[u]));
for(int i=1; i<=n; i++) dis[u][i] = inf, vis[i] = 0; dis[u][a[u]] = 0;
while(!q.empty()){
int x = q.top().second; q.pop();
if(vis[x]) continue; vis[x] = true;
for(int i=A.first[x];i;i=A.nxt[i]){
int t = A.to[i];
if(dis[u][t] > dis[u][x] + (ll)A.w[i]){
dis[u][t] = dis[u][x] + (ll)A.w[i];
if(!vis[t]) q.push(mp(-dis[u][t], t));
}
}
}
}
int main(){
scanf("%d%d", &n, &m);
for(int i=1; i<=n; i++) f[i] = i;
for(int i=1; i<=m; i++){
int x, y, z; scanf("%d%d%d", &x, &y, &z);
A.add(x, y, z); A.add(y, x, z);
int fx = find(x), fy = find(y);
if(fx != fy) f[fx] = fy, B.add(x, y, z), B.add(y, x, z);
else a[++cnt] = x, a[++cnt] = y;
} dep[1] = 1; dfs(1, 0);
for(int i=1; i<=cnt; i++) dijsktra(i);
scanf("%d", &q);
while(q--){
int x, y; scanf("%d%d", &x, &y);
ll ans = d[x] + d[y] - d[lca(x, y)] * 2;
for(int i=1; i<=cnt; i++){
ans = min(ans, dis[i][x] + dis[i][y]);
} printf("%lld\n", ans);
} return 0;
}