\(Tarjan\ O(m + n)\)
\(Tarjan为离线算法\)
\(Tarjan本质上是对向上标记法的优化,首先任取一个点当成根节点向下做dfs,并将所有节点分为三部分\)
\(做法:在回溯的时候更新当前点的祖先,并可计算该点与已经标记为2的距离\)
\(dist[u] + dist[y] - dist[anc] * 2\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 10010, M = N * 2;
int n, m;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
int p[N];
int res[M];
int st[N];
vector<PII> query[N];
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
void dfs(int u, int fa) {
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
dist[j] = dist[u] + w[i];
dfs(j, u);
}
}
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
void tarjan(int u) {
st[u] = 1;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (!st[j]) {
tarjan(j);
p[j] = u;
}
}
for (auto it : query[u]) {
int y = it.x, id = it.y;
if (st[y] == 2) {
int anc = find(y);
res[id] = dist[u] + dist[y] - dist[anc] * 2;
}
}
st[u] = 2;
}
int main() {
IO;
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 0; i < n - 1; ++i) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
if (a != b) {
query[a].pb({b, i});
query[b].pb({a, i});
}
}
for (int i = 1; i <= n; ++i) p[i] = i;
dfs(1, -1);
tarjan(1);
for (int i = 0; i < m; ++i) cout << res[i] << ‘\n‘;
return 0;
}
原文:https://www.cnblogs.com/phr2000/p/14413612.html