[BZOJ2843][LCT]极地旅行社

LCT裸题

#include <cstdio>
#include <algorithm>
#include <iostream>
#define N 30010

using namespace std;

int n,m,tp,x,y;
int A[N],fa[N],ch[N][2],v[N],rev[N],sta[N];
char op[10];

inline int isl(int x){return ch[fa[x]][1]==x;}
inline int isr(int x){return ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x;}

inline void pushdown(int x){
  if(!(x&&rev[x])) return;
  swap(ch[x][0],ch[x][1]);
  if(ch[x][0]) rev[ch[x][0]]^=1;
  if(ch[x][1]) rev[ch[x][1]]^=1;
  rev[x]=0;
}

inline void upd(int x){
  if(!x) return;
  v[x]=A[x];
  if(ch[x][0]) v[x]+=v[ch[x][0]];
  if(ch[x][1]) v[x]+=v[ch[x][1]];
}

inline void rot(int x){
  int y=fa[x],z=fa[y],lor=isl(x);
  if(!isr(y)) ch[z][ch[z][1]==y]=x; fa[x]=z;
  if(ch[y][lor]=ch[x][lor^1]) fa[ch[y][lor]]=y;
  fa[ch[x][lor^1]=y]=x; upd(y); upd(x);
}

inline void splay(int x){
  sta[tp=1]=x;
  for(int i=x;!isr(i);i=fa[i]) sta[++tp]=fa[i];
  for(;tp;--tp) pushdown(sta[tp]);
  for(;!isr(x);rot(x))
    if(!isr(fa[x])) rot(isl(x)^isl(fa[x])?x:fa[x]);
}

inline void access(int x){
  int t=0;
  for(;x;x=fa[x]) splay(x),ch[x][1]=t,t=x,upd(x);
}

inline void reverse(int x){access(x);splay(x);rev[x]^=1;}
inline void link(int x,int y){reverse(x);fa[x]=y;access(x);}
inline void cut(int x,int y){reverse(x);access(y);splay(y);ch[y][0]=fa[x]=0;}
inline int fifa(int x){
  access(x);splay(x);
  while(ch[x][0]) x=ch[x][0];
  return x;
}

inline void reaD(int &x){
  char Ch=getchar();x=0;
  for(;Ch>'9'||Ch<'0';Ch=getchar());
  for(;Ch>='0'&&Ch<='9';x=x*10+Ch-'0',Ch=getchar());
}

int main(){
  freopen("1.in","r",stdin);
  freopen("1.out","w",stdout);
  reaD(n);
  for(int i=1;i<=n;i++) reaD(A[i]);
  reaD(m);
  while(m--){
    scanf("%s",op);
    if(op[0]=='b'){
      reaD(x);reaD(y);
      if(fifa(x)==fifa(y)){puts("no");continue;}
      link(x,y); puts("yes");
    }
    else if(op[0]=='e'){
      reaD(x);reaD(y);
      if(fifa(x)!=fifa(y)){puts("impossible");continue;}
      reverse(x); access(y); splay(y);
      printf("%d\n",v[y]-v[ch[y][1]]);
    }
    else{
      reaD(x);reaD(y);
      access(x); splay(x);
      A[x]=y; upd(x);
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值