bzoj2125 / 迷宫花坛

4 4
1 2 1
2 3 2
1 3 2
3 4 1
2
2 4
1 3

3
2

Solution

#include<bits/stdc++.h>
using namespace std;

#define N 100001
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define drp(i, a, b) for (int i = a; i >= b; i--)
#define fech(i, x) for (int i = 0; i < x.size(); i++)

int x = 0, flag = 1; char ch = getchar(); while(!isdigit(ch)) { if(!(ch ^ '-')) flag = -1; ch = getchar(); }
while(isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar(); return x * flag;
}
inline void write(int x) {
if(!x) { putchar(' '); return; } if(x < 0) putchar('-'), x = -x;
char buf[30] = "", top = 0; while(x) buf[++top] = x % 10 + '0', x /= 10; while(top) putchar(buf[top--]);
}

int n, m;
struct edgeType { int to, dis; }eg[1000001]; int tot;
vector<int> g[N];
int dis[N];
deque<int> q; bool inQue[N];
int dfn[N], ind, dfnDis[N], from[N], fromLen[N], come[N];
bool tag[1000001]; int cnt, Size[N], belong[N];
int fa[N][18], dep[N];

inline void addEdge(int u, int v, int w) {
eg[tot].to = v, eg[tot].dis = w; tot++;
eg[tot].to = u, eg[tot].dis = w; tot++;
g[u].push_back(tot - 2); g[v].push_back(tot - 1);
}

inline void spfa() {
memset(dis, 0x3f3f3f3f, sizeof dis); dis[1] = 0; q.push_back(1); inQue[1] = 1;
while (!q.empty()) {
int u = q.front(), v, w; q.pop_front(); inQue[u] = 0;
fech(i, g[u]) {
int v = eg[g[u][i]].to, w = eg[g[u][i]].dis;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
if (!inQue[v]) {
if (!q.empty() && dis[v] > dis[q.front()]) q.push_back(v);
else q.push_front(v);
}
}
}
}
}

inline void getCir(int u, int targ) {
if (!(u ^ targ)) return;
belong[u] = cnt, Size[cnt] += fromLen[u];
addEdge(u, targ, 0), tag[from[u]] = tag[from[u] ^ 1] = 1;
getCir(come[u], targ);
}

inline void dfs(int u, int f) {
dfn[u] = ++ind; int v, w;
fech(i, g[u]) {
edgeType e = eg[g[u][i]]; if (!(e.to ^ f) || g[u][i] >= (m << 1)) continue;
if (!dfn[e.to])
dfnDis[e.to] = dfnDis[u] + e.dis,
from[e.to] = g[u][i], come[e.to] = u, fromLen[e.to] = e.dis,
dfs(e.to, u);
else if (dfn[e.to] < dfn[u])
tag[g[u][i]] = tag[g[u][i] ^ 1] = 1,
Size[++cnt] = e.dis, getCir(u, e.to);
}
}

inline void dfs2(int u, int f) {
dep[u] = dep[f] + 1; fa[u][0] = f;
rep(i, 1, 17) { if (!fa[u][i - 1]) break; fa[u][i] = fa[fa[u][i - 1]][i - 1]; }
fech(i, g[u]) {
edgeType e = eg[g[u][i]]; if (!(e.to ^ f) || tag[g[u][i]] || dep[e.to]) continue;
dfs2(e.to, u);
}
}

inline int query(int u, int v) {
if (dep[u] < dep[v]) swap(u, v); int a = u, b = v;
drp(i, 17, 0) if (dep[fa[u][i]] >= dep[v]) u = fa[u][i]; if (u == v) return dis[a] - dis[b];
drp(i, 17, 0) if (fa[u][i] ^ fa[v][i]) u = fa[u][i], v = fa[v][i]; int t = fa[u][0];
if (belong[u] && !(belong[u] ^ belong[v])) {
int r = abs(dfnDis[u] - dfnDis[v]);
return dis[a] - dis[u] + dis[b] - dis[v] + min(r, Size[belong[u]] - r);
}
return dis[a] + dis[b] - (dis[t] << 1);
}

int main() {