题目:
题意:
给定一颗树,求任意两点之间的距离
分析:
(1)倍增求LCA:
定义dp[u][x]表示u这个节点向上跳2^x步到达的节点,不包括本身,那么dp[u][0] = fa[u],dfs一遍处理出深度数组deep[u]和dp[u][0]和u到根节点的距离dis[u],求LCA(u,v)时,先使u,v位于同一深度,然后一起向上倍增,预处理O(nlogn),查询O(logn)
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e5+15;
int cnt,head[maxn];
struct edge{
int to,nxt,w;
}e[maxn<<1];
inline void add(int u,int v,int w){
e[++cnt] = (edge){v,head[u],w};
head[u] = cnt;
}
int dp[maxn][20],deep[maxn];
LL dis[maxn];
void dfs(int x,int fa,int depth){
deep[x] = depth;dp[x][0] = fa;
for(int i = head[x]; i;i = e[i].nxt){
int v = e[i].to;
if(v == fa) continue;
dis[v] = dis[x] + e[i].w;
dfs(v,x,depth+1);
}
}
void initdp(int n){ //预处理每个节点向上跳(1<<j)到达的节点
for(int j = 1;(1<<j)-1 <= n; ++j)
for(int i = 1;i <= n; ++i)
dp[i][j] = dp[dp[i][j-1]][j-1];
}
int LCA(int u,int v){
if(deep[u] < deep[v]) swap(u,v);
int