您的位置:首页 > 产品设计 > UI/UE

HUD4010 Query on The Trees

2016-01-03 19:19 531 查看
无事闲来写了一发LCT模板。

然后发现我之前写的LCT各种坑,貌似不支持边权的样子。

于是又找了一个LCT模板,貌似好长的样子。。。。。。。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=300000+5;
int mx
,v
,add
;
int fa
,ch
[2];
bool rev
,root
;
int que
,top;
void pushup(int x){
mx[x]=max(v[x],max(mx[ch[x][0]],mx[ch[x][1]]));
}
void update_add(int x,int d){
if(!x)return ;
mx[x]+=d;
v[x]+=d;
add[x]+=d;
}
void update_rev(int x){
if(!x)return;
rev[x]^=1;
swap(ch[x][1],ch[x][0]);
}
void pushdown(int x){
if(add[x]){
update_add(ch[x][0],add[x]);
update_add(ch[x][1],add[x]);
add[x]=0;
}
if(rev[x]){
update_rev(ch[x][0]);
update_rev(ch[x][1]);
rev[x]=0;
}
}
void rotate(int x){
int y=fa[x],z=fa[y],l=ch[y][1]==x,r=l^1;
if(root[y]){root[y]=false;root[x]=true;}
else ch[z][ch[z][1]==y]=x;
fa[x]=z;fa[y]=x;fa[ch[x][r]]=y;
ch[y][l]=ch[x][r];ch[x][r]=y;
pushup(y);pushup(x);
}
void push(int x){
if(!root[x])push(fa[x]);
pushdown(x);
}
void splay(int x){
push(x);
while(!root[x]){
int y=fa[x],z=fa[y];
if(!root[y]){
if(ch[z][0]==y^ch[y][0]==x)rotate(x);
else rotate(y);
}
rotate(x);
}
}
void access(int x){
for(int t=0;x;x=fa[t=x]){
splay(x);
root[ch[x][1]]=true,root[ch[x][1]=t]=false;
pushup(x);
}
}
void makeroot(int x){
access(x);
splay(x);
update_rev(x);
}
bool judge(int x,int y){
while(fa[x])x=fa[x];
while(fa[y])y=fa[y];
return x==y;
}
void lca(int &u,int &v){
access(v);v=0;
while(u){
splay(u);
if(!fa[u])return;
root[ch[u][1]]=true;
root[ch[u][1]=v]=false;
pushup(u);
u=fa[v=u];
}
}
void cut(int x,int y){
if(x==y||!judge(x,y)){
puts("-1");
return;
}
makeroot(x);
splay(y);
fa[ch[y][0]]=fa[y];
fa[y]=0;
root[ch[y][0]]=true;
ch[y][0]=0;
pushup(y);
}
void link(int x,int y){
if(judge(x,y)){
puts("-1");
return;
}
makeroot(x);
fa[x]=y;
}
void modify(int x,int y,int w){
if(!judge(x,y)){
puts("-1");
return;
}
lca(x,y);
update_add(ch[x][1],w);
update_add(y,w);
v[x]+=w;
pushup(x);
}
void query(int x,int y){
if(!judge(x,y)){
puts("-1");
return;
}
lca(x,y);
printf("%d\n",max(max(mx[ch[x][1]],mx[y]),v[x]));
}
struct Edge{int to,next;}e[N<<1];
int head
,cnt;
void ins(int u,int v){
e[++cnt]=(Edge){v,head[u]};head[u]=cnt;
}
void dfs(int u){
for(int i=head[u];i;i=e[i].next){
if(e[i].to==fa[u])continue;
fa[e[i].to]=u;
dfs(e[i].to);
}
}
int main(){
int n;
while(scanf("%d",&n)==1){
cnt=0;
for(int i=0;i<=n;i++){
head[i]=mx[i]=v[i]=add[i]=fa[i]=ch[i][0]=ch[i][1]=rev[i]=0;
root[i]=true;
}
mx[0]=-2000000000;
int x,y;
for(int i=1;i<n;i++){
scanf("%d%d",&x,&y);
ins(y,x);ins(x,y);
}
for(int i=1;i<=n;i++){
scanf("%d",&v[i]);
mx[i]=v[i];
}
dfs(1);
int q,opt,w;
scanf("%d",&q);
while(q--){
scanf("%d",&opt);
if(opt!=3)
scanf("%d%d",&x,&y);
if(opt==1)link(x,y);
if(opt==2)cut(x,y);
if(opt==3)scanf("%d%d%d",&w,&x,&y),modify(x,y,w);
if(opt==4)query(x,y);
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: