https://www.luogu.org/problemnew/show/P3379

求 a 和 b 的 LCA

考虑先 access(a),此时 a 和 root 在一条链上,再 access(b) 记录最后一个被 access 遇到的点,即为 LCA

因为LCT常数太大所以要开O2才能过

#include <bits/stdc++.h>
using namespace std; const int N = 500000 + 10; int fa[N], ch[N][2], val[N], rev[N], st[N], n, m, root, len; int isroot(int u) {
return ch[fa[u]][0] != u && ch[fa[u]][1] != u;
} int get(int u) {
return ch[fa[u]][1] == u;
} void pushdown(int u) {
if(rev[u]) {
swap(ch[u][0], ch[u][1]);
rev[ch[u][0]] ^= 1;
rev[ch[u][1]] ^= 1;
rev[u] ^= 1;
}
} void rotate(int u) {
int old = fa[u], oldd = fa[old], k = get(u);
if(!isroot(old)) ch[oldd][get(old)] = u; fa[u] = oldd;
fa[ch[u][k ^ 1]] = old; ch[old][k] = ch[u][k ^ 1];
fa[old] = u; ch[u][k ^ 1] = old;
} void splay(int u) {
st[len = 1] = u;
for(int i = u; !isroot(i); i = fa[i]) st[++len] = fa[i];
for(int i = len; i >= 1; i--) pushdown(st[i]);
for(; !isroot(u); rotate(u)) if(!isroot(fa[u])) rotate(get(u) == get(fa[u]) ? fa[u] : u);
} int access(int u) {
int tmp;
for(int i = 0; u; i = u, u = fa[u]) {
splay(u);
ch[u][1] = i;
tmp = u;
}
return tmp;
} void makeroot(int u) {
access(u);
splay(u);
rev[u] ^= 1;
} void link(int x, int y) {
makeroot(x);
fa[x] = y;
} int main() {
scanf("%d %d %d", &n, &m, &root);
for(int i = 1; i < n; i++) {
int a, b;
scanf("%d %d", &a, &b);
link(a, b);
}
makeroot(root);
for(int i = 1; i <= m; i++) {
int a, b;
scanf("%d %d", &a, &b);
access(a); printf("%d\n", access(b));
}
return 0;
}

最新文章

  1. pythonchallenge 解谜 Level 2
  2. windows查看端口占用以及关闭相应的进程
  3. ASP.NET Core重写个人博客站点小结
  4. HttpServletRequest 中 getRequestURL和getRequestURI的区别
  5. spring_150801_autowired_qualifier
  6. C语言位运算符:与、或、异或、取反,左移和右移
  7. linux中 ECShop的文件不能写
  8. codevs 1540 银河英雄传说
  9. 【模拟】Codeforces 691B s-palindrome
  10. xp多网卡静态路由设置方法
  11. 深度克隆---js对象引用
  12. HDOJ2031进制转换
  13. js函数基础知识
  14. Apache Spark 2.2.0 中文文档 - SparkR (R on Spark) | ApacheCN
  15. Linux基础二
  16. 菜鸟安卓学习路——更强大的滚动控件--RecycleView
  17. Apache Solr入门教程(转)
  18. turnserver 配置说明记录
  19. Spark设计理念与基本架构
  20. linux 程序无缘无故推出 没有core文件 broken pipe Resource temporarily unavailable

热门文章

  1. LinqHelper连接数据库配置
  2. Halcon的HWindowControl控件在WinForm程序中的使用介绍(重点解决图片缩放的问题)
  3. Burpsuite模块—-Intruder模块详解
  4. SQL和NoSQL
  5. Spring总结六:AOP(面向切面编程)
  6. Java对象的强、软、弱和虚引用
  7. 深入剖析SolrCloud(四)
  8. solrcloud使用问题记录
  9. 简单的互斥同步方式——synchronized关键字详解
  10. yii2 源码分析1从入口开始