# 【BZOJ2125】【仙人掌】最短路 题解

Description

Input

Output

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

#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() {
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;
}

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客