BZOJ 4668: 冷战 并查集启发式合并/LCT
2024-10-07 02:26:23
挺好想的,最简单的方法是并查集启发式合并,加暴力跳父亲。
然而,这个代码量比较小,比较好写,所以我写了 LCT,更具挑战性。
#include <cstdio>
#include <algorithm>
#define N 1000004
#define lson t[x].ch[0]
#define rson t[x].ch[1]
#define setIO(s) freopen(s".in","r",stdin)
using namespace std;
int sta[N],n,m,p[N];
struct Node {
int ch[2],max,val,rev,f;
}t[N];
int find(int x) {
return p[x]==x?x:p[x]=find(p[x]);
}
int get(int x) {
return t[t[x].f].ch[1]==x;
}
int isrt(int x) {
return !(t[t[x].f].ch[0]==x||t[t[x].f].ch[1]==x);
}
void pushup(int x) {
t[x].max=t[x].val;
t[x].max=max(max(t[lson].max,t[rson].max), t[x].max);
}
void mark(int x) {
if(!x) return;
swap(lson, rson), t[x].rev^=1;
}
void pushdown(int x) {
if(t[x].rev) mark(lson), mark(rson), t[x].rev=0;
}
void rotate(int x) {
int old=t[x].f,fold=t[old].f,which=get(x);
if(!isrt(old))
t[fold].ch[t[fold].ch[1]==old]=x;
t[old].ch[which]=t[x].ch[which^1], t[t[old].ch[which]].f=old;
t[x].ch[which^1]=old,t[old].f=x,t[x].f=fold;
pushup(old),pushup(x);
}
void splay(int x) {
int v=0,u=x,fa;
for(sta[++v]=u;!isrt(u);u=t[u].f) sta[++v]=t[u].f;
for(int i=v;i>=1;--i) pushdown(sta[i]);
for(u=t[u].f;(fa=t[x].f)!=u;rotate(x))
if(t[fa].f!=u)
rotate(get(fa)==get(x)?fa:x);
}
void Access(int x) {
for(int y=0;x;y=x,x=t[x].f) {
splay(x),rson=y,pushup(x);
}
}
void makeroot(int x) {
Access(x),splay(x),mark(x);
}
void split(int x,int y) {
makeroot(x),Access(y),splay(y);
}
void link(int x,int y) {
makeroot(x), makeroot(y),t[x].f=y;
}
int main() {
int i,j,cc=0;
scanf("%d%d",&n,&m);
for(i=1;i<=n;++i) p[i]=i;
int lastans=0,tot=n;
for(i=1;i<=m;++i) {
int op,x,y;
scanf("%d%d%d",&op,&x,&y);
x^=lastans,y^=lastans;
if(op==0) {
++cc;
x=find(x),y=find(y);
if(x!=y) {
++tot;
p[x]=p[y]=p[tot]=tot;
t[tot].val=cc;
link(x,tot),link(tot,y);
}
}
else {
int xx=find(x),yy=find(y);
if(xx!=yy) printf("0\n"),lastans=0;
else {
split(x,y);
printf("%d\n",lastans=t[y].max);
}
}
}
return 0;
}
最新文章
- Spring4.X——搭建
- [游戏模版21] Win32 物理引擎 能量守恒
- IOS开发 应用程序图标数字角标
- history介绍及bash命令快速调用
- scala言语基础学习九
- 一个快速、完善的Android开发框架整合实践(QuickAndroid)
- java小程序 质数
- springmvc在web.xml中的配置
- CSS3之渐变效果
- java操作mysql的增删改查
- python3语法小记(二)列表 和 元组
- android如何使用自己定义JNI接口,以及NDK环境建设和使用的工具。
- Spring3+SpingMVC+Hibernate4全注解环境配置
- 咸鱼入门到放弃4——Http协议
- mysql导出导入数据无权限
- JavaScript获取元素CSS计算后的样式
- 常用工具类(System,Runtime,Date,Calendar,Math)
- LINQ技术
- 关于SpringMVC
- Flask核心机制--上下文源码剖析
热门文章
- Android layout_marginBottom无效
- redis在php中实际应用-hash
- python基础数据类型和初级应用
- 纯CSS实现tag彩色标签
- MySQL安装过程中遇到的错误代码为1045的解决方法
- O024、Nova组件如何协同工作
- 分布式的几件小事(九)zookeeper都有哪些使用场景
- springboot日志框架学习------slf4j和log4j2
- Spring的基本应用(1):依赖以及控制反转
- 使输入框(input &#160;&; textarea)变为只可读状态readonly=";readonly";,禁用输入框disabled=";disabled";