洛谷:P3690 【模板】Link Cut Tree (动态树)

/*诸多细节,不注意就会调死去! 见注释。*/
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN=;
int n,m;
int fa[MAXN],rev[MAXN],val[MAXN],xr[MAXN],Q[MAXN],ch[MAXN][];
bool isroot(int x){ return ch[fa[x]][]!=x && ch[fa[x]][]!=x; }
void Update(int x){ xr[x]=xr[ch[x][]]^xr[ch[x][]]^val[x]; }
bool get(int x){ return ch[fa[x]][]==x ;}
void Down(int x){ if(rev[x]){ rev[ch[x][]]^=; rev[ch[x][]]^=; rev[x]^=; swap(ch[x][],ch[x][]); } }
void Rotate(int x)
{
int old=fa[x],oldf=fa[old],op=get(x);
if(!isroot(old)) ch[oldf][ch[oldf][]==old]=x; //这一条一定要放在改变父子关系之前!在纯Splay中是放在后面的,因为直接看oldf是否为0可知old是否为根。
ch[old][op]=ch[x][op^]; fa[ch[x][op^]]=old; //但这里使用isroot,改变之后就不能判断了!
ch[x][op^]=old; fa[old]=x; fa[x]=oldf;
Update(old); Update(x);
}
void Splay(int x)
{
int tp=; Q[]=x;
for(int i=x;!isroot(i);i=fa[i]) Q[++tp]=fa[i]; //对于LCT的判断是否是根节点,需要使用isroot,在纯Splay中使用的是fa,不要搞混!
for(int i=tp;i;i--) Down(Q[i]);
for(int FA; !isroot(x) ; Rotate(x))
{
FA=fa[x];
if(!isroot(FA))
Rotate(get(x)==get(FA)?FA:x);
}
}
void Access(int x){ int t=; while(x){ Splay(x); ch[x][]=t; Update(x); t=x; x=fa[x]; } } //记得Update
void Makeroot(int x){ Access(x); Splay(x); rev[x]^=;}
void Link(int x,int y){ Makeroot(x); fa[x]=y; }
void Cut(int x,int y){ Makeroot(x); Access(y); Splay(y); if(ch[y][]==x) fa[x]=ch[y][]=;}
int Find(int x){ Access(x); Splay(x); while(ch[x][]) x=ch[x][]; return x; }
int main()
{
scanf("%d%d",&n,&m);
for(int i=;i<=n;i++) scanf("%d",&val[i]) , xr[i]=val[i];
while(m--)
{
int x,y,op;
scanf("%d%d%d",&op,&x,&y);
if(op==){ Makeroot(x); Access(y); Splay(y); printf("%d\n",xr[y]); }
if(op==){ if(Find(x)!=Find(y)) Link(x,y); }
if(op==){ Cut(x,y); }
if(op==){ Makeroot(x); val[x]=y; Update(x); }
}
return ;
}

最新文章

  1. ngx_http_fastcgi_module模块.md
  2. VS调试程序时一闪而过的问题-解决方法(网上搜集)
  3. 手机设备连接eclipse的问题
  4. 网格弹簧质点系统模拟(Spring-Mass System by Verlet Integration)附源码
  5. Linux下C++静态库、动态库的制作与使用
  6. http://stackoverflow.com/questions/6065169/requestanimationframe-with-this-keyword
  7. CGContextRef 绘图
  8. git 基本配置及使用
  9. 2016-03-10:libx265源码解析
  10. leetcode 刷道题 70 earch Insert Position 二进制搜索插入位置
  11. C#操作xml文件进行增、删、改
  12. “java.lang.IllegalArgumentException: Failed to evaluate expression ‘ROLE_USER’”报错的解决
  13. ab返回结果参数分析
  14. day6(列表操作、列表练习题)
  15. python学习日记(面向对象——组合)
  16. JQ-bootstrap我的开源前端框架
  17. Shell 同步时间脚本
  18. windows下安装Erlang
  19. 【转载,整理】Linux性能监控
  20. Codeforces 559B - Equivalent Strings

热门文章

  1. 九度OJ 1098:字母统计 (计数)
  2. Go Concurrency Patterns: Timing out, moving on
  3. Android笔记之自定义对话框
  4. Windows消息、绘图与多线程
  5. appium()-The event firing
  6. Ace(二)Demo示例
  7. Ubuntu下安装Android studio【转】
  8. 详细阐述ping命令中请求超时与无法访问的区别
  9. 基于BASYS2的VHDL程序与烧写——按键消抖程序
  10. hadoop集群异常问题总结