Description
幻想世界里有一片森林,森林里自然有许多许多树… 题目描述
我们定义对一棵树做一次变换的含义为:当以 1 号节点为根时,交换两个互相
不为祖先的点的子树;
一棵树的权值为对它进行至多一次变换能得到的最大直径长度;
初始时你只有一个节点 1,你需要执行 n-1 个操作,第 i 次操作会给出一个整
数 x,表示新加入第 i+1 号点,并与第 x 号点连一条边。每次操作后输出当前的树
的权值。
由于某些原因我们对数据进行了强制在线处理
n
≤
2
⋅
1
0
5
n\le2\cdot10^5
n≤2⋅105
Solution
首先这题的数据非常sb,不是所有的点都有数据编号的。。
可以发现我们一定是选直径的一个端点和某个节点交换,再讨论一下可以发现“某个节点”的父亲一定在直径上(不然选它的父亲可以更长)
于是我们维护一下直径的两个端点(u,v),维护一下这个交换节点的最下端p。具体说就是先用i更新(u,v),然后用换下来的点更新p。由于强制在线所以我们需要写一个LCT来求树上距离
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
const int N=500005;
struct treeNode {int son[2],fa,size,rev,is_root;} t[N];
int read() {
int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}
void push_up(int x) {
t[x].size=1;
if (t[x].son[0]) t[x].size+=t[t[x].son[0]].size;
if (t[x].son[1]) t[x].size+=t[t[x].son[1]].size;
}
void push_down(int x) {
if (!t[x].rev||!x) return ;
t[x].rev=0; std:: swap(t[x].son[0],t[x].son[1]);
if (t[x].son[0]) t[t[x].son[0]].rev^=1;
if (t[x].son[1]) t[t[x].son[1]].rev^=1;
}
void rotate(int x) {
if (t[x].is_root) return ;
int y=t[x].fa,z=t[y].fa;
int k=t[y].son[1]==x;
t[y].son[k]=t[x].son[!k];
if (t[x].son[!k]) t[t[x].son[!k]].fa=y;
t[y].fa=x; t[x].son[!k]=y;
t[x].fa=z;
if (t[y].is_root) {
t[x].is_root=1;
t[y].is_root=0;
} else t[z].son[t[z].son[1]==y]=x;
push_up(y); push_up(x);
}
void remove(int x) {
if (!t[x].is_root) remove(t[x].fa);
push_down(x);
}
void splay(int x) {
remove(x);
for (;!t[x].is_root;) {
int y=t[x].fa,z=t[y].fa;
if (!t[y].is_root) {
if ((t[z].son[1]==y)^(t[y].son[1]==x)) rotate(x);
else rotate(y);
}
rotate(x);
}
}
void access(int x) {
int y=0;
while (x) {
splay(x);
t[t[x].son[1]].is_root=1;
t[t[x].son[1]=y].is_root=0;
push_up(x); y=x; x=t[x].fa;
}
}
void mroot(int x) {
access(x); splay(x); t[x].rev^=1;
}
void link(int x,int y) {
mroot(x); t[x].fa=y;
}
void cut(int x,int y) {
mroot(x); access(y); splay(y);
t[y].son[0]=t[x].fa=0;
t[x].is_root=1; push_up(y);
}
int get_dis(int x,int y) {
mroot(x); access(y); splay(y);
return t[y].size-1;
}
int main(void) {
freopen("data.in","r",stdin);
freopen("myp.out","w",stdout);
int n=read(),lastans=0;
if (n<=6) n=read();
rep(i,1,n) t[i].is_root=1,t[i].size=1;
int u=1,v=1,p=1;
rep(i,2,n) {
int x=read()^lastans;
link(x,i); int flag=0;
int l=get_dis(u,v),lu=get_dis(i,u),lv=get_dis(i,v);
int a=u,b=v,c=i;
if (lu>l) u=c,v=a,l=lu,flag=1;
if (lv>l) u=c,v=b,l=lv,flag=2;
if (!flag) {
int pu=get_dis(u,p);
int pv=get_dis(v,p);
if ((pu+pv-l)/2<(lu+lv-l)/2) p=i;
} else {
int pu=get_dis(u,p);
int pv=get_dis(v,p);
if (flag==1) {
if ((pu+pv-l)/2<(get_dis(b,u)+get_dis(b,v)-l)/2) p=b;
} else {
if ((pu+pv-l)/2<(get_dis(a,u)+get_dis(a,v)-l)/2) p=a;
}
}
int pu=get_dis(u,p);
int pv=get_dis(v,p);
if ((pu+pv-l)/2==0) printf("%d\n", lastans=l);
else printf("%d\n", lastans=l+(pu+pv-l)/2-1);
}
return 0;
}