Description
给一个N个点M条边的连通无向图,满足每条边最多属于一个环,有Q组询问,每次询问两点之间的最短路径。
Input
输入的第一行包含三个整数,分别表示N和M和Q 下接M行,每行三个整数v,u,w表示一条无向边v-u,长度为w 最后Q行,每行两个整数v,u表示一组询问
Output
输出Q行,每行一个整数表示询问的答案
Sample Input
9 10 2
1 2 1
1 4 1
3 4 1
2 3 1
3 7 1
7 8 2
7 9 2
1 5 3
1 6 4
5 6 1
1 9
5 7
Sample Output
5
6
HINT
对于100%的数据,N<=10000,Q<=10000
考虑特判环上状态,以第一个dfs到的点作为father,求最短路。
之后就可以将图视为一棵树,跳倍增。
#include <bits/stdc++.h>
#define clr(x) memset(x, 0, sizeof x)
using namespace std;
template <class T> inline void read(T &x) {
int flag = 1; x = 0;
register char ch = getchar();
while(ch < '0' || ch > '9') { if(ch == '-') flag = -1; ch = getchar(); }
while(ch >= '0' && ch <= '9') { x = (x<<1)+(x<<3)+ch-'0'; ch = getchar(); }
x *= flag;
}
const int N = 10005, M = 100005;
int n,m,q,e,ti,cn;
int hd[N],nx[M],to[M],w[M],dl[M],dfn[N],st[N],d[N],v[N],rd[N],dp[N],bl[N],ln[N],f[N][14];
inline void add(int x, int y, int z) { to[++e] = y, w[e] = z, nx[e] = hd[x], hd[x] = e; }
void spfa() {
clr(d);
queue<int> q; q.push(1), d[1] = 0;
while(!q.empty()) {
int u = q.front(); q.pop(); v[u] = 0;
for(int i = hd[u]; i; i = nx[i]) if(d[to[i]] > d[u]+w[i]) {
d[to[i]] = d[u]+w[i];
if(!v[to[i]]) v[to[i]] = 1, q.push(to[i]);
}
}
}
void find(int x, int y) {
if(x == y) return;
bl[x] = cn, add(y, x, 0), dl[st[x]] = dl[st[x]^1] = 1, ln[cn] += w[st[x]], find(to[st[x]^1], y);
}
void dfs(int x) {
dfn[x] = ++ti;
for(int i = hd[x]; i; i = nx[i]) if(i != (st[x]^1) && i <= (m<<1)+1) {
if(!dfn[to[i]]) rd[to[i]] = rd[x]+w[i], st[to[i]] = i, dfs(to[i]);
else if(dfn[to[i]] < dfn[x]) ln[++cn] = w[i], find(x, to[i]);
}
}
void dfs2(int x) { for(int i = hd[x]; i; i = nx[i]) if(!dl[i] && !dp[to[i]]) f[to[i]][0] = x, dp[to[i]] = dp[x]+1, dfs2(to[i]); }
int qry(int x, int y) {
if(dp[x] < dp[y]) swap(x, y);
int a = x, b = y;
for(int i = 13; i; i--) if(dp[f[x][i]] >= dp[y]) x = f[x][i];
if(x == y) return d[a]-d[b];
for(int i = 13; i; i--) if(f[x][i]^f[y][i]) x = f[x][i], y = f[y][i];
if(bl[x] && bl[x] == bl[y]) {
int r = abs(rd[x]-rd[y]);
return d[a]-d[x]+d[b]-d[y]+min(r, ln[bl[x]]-r);
}
return d[a]+d[b]-d[f[x][0]]<<1;
}
int main() {
read(n); read(m); read(q);
for(int x, y, z, i = 1; i <= m; i++) read(x), read(y), read(z), add(x, y, z), add(y, x, z);
spfa();
dfs(1);
dp[1] = 1;
dfs2(1);
for(int j = 1; j < 14; j++) for(int i = 1; i <= n; i++) f[i][j] = f[f[i][j-1]][j-1];
for(int x, y, i = 1; i <= q; i++) read(x), read(y), printf("%d\n",qry(x, y));
return 0;
}