倍增LCA模板

来源:互联网 发布:国航网上值机软件 编辑:程序博客网 时间:2024/06/05 10:46
const int M = 20;struct node{int v, value, next;}p[maxn << 1];int len, head[maxn], dis[maxn], depth[maxn], n, m, father[maxn][25];void addedge(int u, int v, int value){p[len].v = v;p[len].value = value;p[len].next = head[u];head[u] = len++;}void dfs(int x, int fa){father[x][0] = fa;for (int i = head[x]; ~i; i = p[i].next){if (p[i].v == fa)continue;dis[p[i].v] = dis[x] + p[i].value;depth[p[i].v] = depth[x] + 1;dfs(p[i].v, x);}}void presolve(){dis[1] = depth[1] = 0;dfs(1, 0);for (int i = 1; i < M; i++)          for (int j = 1; j <= n; j++)              father[j][i] = father[father[j][i - 1]][i - 1];  }int lca(int x, int y){if (depth[x] != depth[y]){if (depth[x] > depth[y])swap(x, y);int distant = depth[y] - depth[x];for (int i = 0; i < M; i++){if (distant&(1 << i))y = father[y][i];}}if (x == y)return x;for (int i = M; i >= 0; i--){if (father[x][i] != father[y][i]){x = father[x][i];y = father[y][i];}}return father[x][0];}int query(int x, int y){return dis[x] + dis[y] - (dis[lca(x, y)] << 1);}

原创粉丝点击