1. 程式人生 > 實用技巧 >How far away ? 樹上求兩點之間最短距離(用LCA)

How far away ? 樹上求兩點之間最短距離(用LCA)

How far away ?

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <queue>
#include <map>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <numeric>
#include <cmath>
#include 
<iomanip> #include <deque> #include <bitset> #include <cassert> //#include <unordered_set> //#include <unordered_map> #define ll long long #define pii pair<int, int> #define rep(i,a,b) for(int i=a;i<=b;i++) #define dec(i,a,b) for(int i=a;i>=b;i--) #define
forn(i, n) for(int i = 0; i < int(n); i++) using namespace std; int dir[4][2] = { { 1,0 },{ 0,1 } ,{ 0,-1 },{ -1,0 } }; const long long INF = 0x7f7f7f7f7f7f7f7f; const int inf = 0x3f3f3f3f; const double pi = acos(-1.0); const double eps = 1e-6; const int mod = 1e9 + 7; inline ll read() { ll x
= 0; bool f = true; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = false; c = getchar(); } while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); return f ? x : -x; } inline ll gcd(ll m, ll n) { return n == 0 ? m : gcd(n, m % n); } void exgcd(ll A, ll B, ll& x, ll& y) { if (B) exgcd(B, A % B, y, x), y -= A / B * x; else x = 1, y = 0; } inline int qpow(int x, ll n) { int r = 1; while (n > 0) { if (n & 1) r = 1ll * r * x % mod; n >>= 1; x = 1ll * x * x % mod; } return r; } inline int inv(int x) { return qpow(x, mod - 2); } ll lcm(ll a, ll b) { return a * b / gcd(a, b); } /**********************************************************/ const int N = 4e4 + 5; int f[N][31],cost[N][31],dep[N]; void dfs(int v, int pa, vector<vector<int>>& g, vector<vector<int>>& w) { f[v][0] = pa; dep[v] = dep[pa] + 1; for (int i = 1; i < 31; i++) { f[v][i] = f[f[v][i - 1]][i - 1];//x的2^i祖先是它2^i-1祖先的2^i-1祖先 cost[v][i] = cost[f[v][i - 1]][i - 1] + cost[v][i - 1];//x到它2^i祖先的距離 = x到它2^i-1祖先的距離 + x的2^i-1祖先到它2^i-1祖先距離 } for (int i = 0; i < g[v].size(); i++) { int to = g[v][i]; if (to != pa) { cost[to][0] = w[v][i]; dfs(to, v, g, w); } } } int lca(int x, int y) { if (dep[x] > dep[y]) swap(x, y); int tmp = dep[y] - dep[x], ans = 0; for (int j = 0; tmp; j++, tmp >>= 1) if (tmp & 1) ans += cost[y][j], y = f[y][j]; if (y == x) return ans; for (int j = 30; j >= 0 && y != x; j--) { if (f[x][j] != f[y][j]) { ans += cost[x][j] + cost[y][j]; x = f[x][j]; y = f[y][j]; } } ans += cost[x][0] + cost[y][0]; return ans; } int main() { ios::sync_with_stdio(false);cin.tie(nullptr); cout.tie(nullptr); int T; cin >> T; while (T--) { int n, m; cin >> n >> m; vector<vector<int>> g(n + 1), w(n + 1); rep(i, 1, n - 1) { int u, v, d; cin >> u >> v >> d; g[u].push_back(v); g[v].push_back(u); w[u].push_back(d); w[v].push_back(d); } dfs(1, -1, g, w); rep(i, 1, m) { int u, v; cin >> u >> v; cout << lca(u, v) << endl; } } }