Codeforces 832 D. Misha, Grisha and Underground 倍增法求LCA
来源:互联网 发布:风水织梦网站源码 编辑:程序博客网 时间:2024/06/05 09:18
传送门:Codeforces 832D
题意:给出一棵n个节点的树,然后给出m个三元组(i,j,k),将其中两个点做起点另一个点做终点,问两条路径的公共部分最大是多少。
思路:很明显要求lca,我用了较为简单的倍增法求,然后就是对给出的三个点枚举终点,求一个最大值,求两条路径的公共部分的时候有思维点,需要仔细思考一下,有必要画个图思考一下两条路径的相交可能出现的情况。
代码:
#include<bits/stdc++.h>using namespace std;#define rank Rank#define pb push_back #define MAXN 100050#define inf 0x3f3f3f3ftypedef pair<int,int>P;int rank[MAXN],f[MAXN],dep[MAXN];int pre[20][MAXN],dp[20][MAXN];int n,m;vector<int>g[MAXN];void dfs(int u, int fa){ dep[u] = dep[fa] + 1; for(int i=0;i<g[u].size();i++) { int v = g[u][i]; if(v == fa) continue; dfs(v, u); pre[0][v] = u; }} int lca(int u, int v,int MAX){if(u==v)return u; int ans = inf; if(dep[u] < dep[v]) swap(u, v); int k = dep[u] - dep[v]; for(int i=0;i<MAX;i++) { if((k>>i)&1) u = pre[i][u]; } if(u == v)return u; for(int i=MAX-1;i>=0;i--) if(pre[i][u] != pre[i][v]) { u = pre[i][u]; v = pre[i][v]; } return pre[0][u];}int solve(int f, int s, int t, int k){int x = lca(s, t, k);int y = lca(f, s, k);int z = lca(f, t, k);int w;if(dep[x] > dep[y]) w = x;else w = y;if(dep[z] > dep[w]) w = z;int root = lca(w, f, k);return dep[w] - dep[root] + dep[f] - dep[root] + 1;}int main(){ int q,u,v,w; scanf("%d%d",&n,&q); { for(int i=2;i<=n;i++) scanf("%d",&u),g[i].push_back(u),g[u].push_back(i); dep[1] = 1; dfs(1, 0); int k = 0,t = 1; while(t <= n)t <<= 1,k++; for(int i=0;i+1<k;i++) { for(int j=1;j<=n;j++) { pre[i+1][j] = pre[i][pre[i][j]]; } } while(q--) { int ans = 0,res = 0; scanf("%d%d%d",&u,&v,&w); ans = max(solve(u, v, w, k), ans); ans = max(solve(v, w, u, k), ans); ans = max(solve(w, u, v, k), ans); printf("%d\n",ans); } }}
阅读全文
0 0
- Codeforces 832 D. Misha, Grisha and Underground 倍增法求LCA
- 【Lca 倍增】codeforces 832D Misha, Grisha and Underground
- codeforces 832D Misha, Grisha and Underground 倍增lca
- cf 832D Misha, Grisha and Underground 【lca+倍增】
- codeforces D. Misha, Grisha and Underground(LCA)
- codeforces 832 D Misha, Grisha and Underground(倍增)
- Codeforces 832D-Misha, Grisha and Underground(LCA)
- Codeforces 832D. Misha, Grisha and Underground【LCA】
- Codeforces 832D Misha, Grisha and Underground【LCA】
- CodeForces 832D Round #425 D Misha, Grisha and Underground :LCA求树上路径长度
- D. Misha, Grisha and Underground(LCA 倍增)
- codeforces 832D Misha, Grisha and Underground
- Codeforces 832D Misha, Grisha and Underground
- [codeforces 832D]Misha, Grisha and Underground
- 【Codeforces】832D. Misha, Grisha and Underground
- Codeforces-832D-Misha, Grisha and Underground
- CF 832D Misha, Grisha and Underground(Tree+lca)
- CF --- 832D Misha, Grisha and Underground 【LCA + 思维】
- jQuery实现栏目切换
- 1011.KazaQ's Socks
- js请求
- 51nod 1629 B君的圆锥
- 实现右旋、左旋循环移位函数
- Codeforces 832 D. Misha, Grisha and Underground 倍增法求LCA
- leetcode#155. Min Stack
- 《最强大脑——77招让你成为脑力最好的人》读书笔记
- A
- mysqldump全备份及结合binlog日志恢复的全过程 (转)
- 熊大UWB系列教程二:KEIL软件环境搭建以及程序下载
- 《Inside C#》笔记(十五) 非托管代码 下
- mybatis新增(三)
- 转载 MYSQL协议分析