1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130 | #include <bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define ll long long
inline int read(){
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
struct edge{
int v,w;
edge(int v=0,int w=0):v(v),w(w){}
};
using namespace std;
const int N=1e5+5;
int n,m,q,ans;
int dfn[N],low[N],dfc,cnt;
int fa[N],top[N],son[N],size[N],dep[N],b[N],sum[N],dis[N];
vector<edge> G[N],T[N<<1];
inline int min(int a,int b){return a<b?a:b;}
inline void solve(int u,int v,int w){
++cnt;
int pw,pre=w,i=v;
while(i!=fa[u]){
sum[i]=pre;
pre+=b[i];
i=fa[i];
}
sum[cnt]=sum[u];//把整个环的边权和存到方点上
sum[u]=0;
i=v;
while(i!=fa[u]){
pw=min(sum[i],sum[cnt]-sum[i]);
//找最短路建树边
T[cnt].push_back({i,pw});
T[i].push_back({cnt,pw});
i=fa[i];
}
}
void Tarjan(int u,int f) {
low[u] = dfn[u] = ++dfc;
int v,w,l=G[u].size();
for (int i=0;i<l;i++) {
v=G[u][i].v;
if(v==f)continue;
w=G[u][i].w;
if (!dfn[v]) {
fa[v]=u,b[v]=w;//把u->v的边权存到v上
Tarjan(v,u);
low[u] = min(low[u], low[v]);
} else low[u] = min(low[u], dfn[v]);
if(low[v]<=dfn[u])continue;
//圆点之间的连边,保留原图中数据
T[u].push_back({v,w});T[v].push_back({u,w});
}
for(int i=0;i<l;i++){
v=G[u][i].v;
if(fa[v]==u||dfn[v]<=dfn[u])continue;
//找到非树边,然后建方点并连边
solve(u,v,G[u][i].w);
}
}
void dfs1(int u,int f){
fa[u] = f;
dep[u] = dep[f]+1;
size[u] = 1;
int v,t = -1,l = T[u].size();
for(int i=0;i<l;++i){
v = T[u][i].v;
if(v==f) continue;
dis[v] = dis[u]+T[u][i].w;
dfs1(v,u);
size[u] += size[v];
if(size[v]>t){
t = size[v];
son[u] = v;
}
}
}
void dfs2(int u,int f){
top[u] = f;
if(son[u]==0) return;
dfs2(son[u],f);
int v,l = T[u].size();
for(int i=0;i<l;++i){
v = T[u][i].v;
if(v==fa[u]||v==son[u]) continue;
dfs2(v,v);
}
}
inline int lca(int u,int v){
while(top[u]!=top[v]){
if(dep[top[u]]<dep[top[v]])swap(u,v);
u=fa[top[u]];
}
return dep[u]<dep[v]?u:v;
}
inline int find(int u,int f){
int res;
while(top[u]!=top[f]){
res=top[u];
u=fa[top[u]];
}
return u==f?res:son[f];
}
int main(){
n=read(),m=read(),q=read();
cnt=n;
rep(i,1,m){
int u=read(),v=read(),w=read();
G[u].push_back({v,w});G[v].push_back({u,w});
}
Tarjan(1,0);
dfs1(1,0);
dfs2(1,1);
while(q--){
int u=read(),v=read();
int p=lca(u,v);
if(p<=n)ans=dis[u]+dis[v]-dis[p]*2;//lca为圆点
else{
int A=find(u,p),B=find(v,p);//找到儿子A,B
ans=dis[u]+dis[v]-dis[A]-dis[B];
if(sum[A]<sum[B])swap(A,B);
ans+=min(sum[A]-sum[B],sum[p]+sum[B]-sum[A]);
}
printf("%d\n",ans);
}
return 0;
}
|