SPOJ 375 Query on a tree 树链剖分模板

时间:2023-03-09 15:02:54
SPOJ 375 Query on a tree 树链剖分模板
第一次写树剖~

#include<iostream>
#include<cstring>
#include<cstdio>
#define L(u) u<<1
#define R(u) u<<1|1
using namespace std;
const int MAX=;
int t,head[MAX*],next1[MAX*],tov[MAX*],val[MAX*],tot,n;
int fa[MAX],w[MAX],son[MAX],depth[MAX],tot2,size[MAX];
int d[MAX][],tree[MAX*],top[MAX];
char ch[];
inline void swap(int &a,int &b)
{
int t;
t=a;
a=b;
b=t;
}
inline void add(int a,int b,int c)
{
tot++;
next1[tot]=head[a];
head[a]=tot;
tov[tot]=b;
val[tot]=c;
}
inline void dfs1(int k)
{
son[k]=;
size[k]=;
for (int i=head[k];i;i=next1[i])
{
int v=tov[i];
if (v!=fa[k])
{
fa[v]=k;
depth[v]=depth[k]+;
dfs1(v);
son[k]=size[v]<size[son[k]]?son[k]:v;
size[k]+=size[v];
}
}
}
inline void dfs2(int k,int _top)
{
w[k]=++tot2;
top[k]=_top;
if (son[k]!=) dfs2(son[k],_top);//the same _top
for (int i=head[k];i;i=next1[i])
{
int v=tov[i];
if (v!=fa[k]&&v!=son[k])
dfs2(v,v);//the new _top;
}
}
inline void update(int u,int l,int r,int loc,int _value)
{
if (l==loc&&r==loc)
{
tree[u]=_value;
return ;
}
int mid=(l+r)>>;
if (loc<=mid) update(L(u),l,mid,loc,_value);
else update(R(u),mid+,r,loc,_value);
tree[u]=max(tree[R(u)],tree[L(u)]);//pushup
}
void doit()
{
memset(head,,sizeof(head));
memset(depth,,sizeof(depth));
memset(fa,,sizeof(fa));
memset(tree,,sizeof(tree));
tot2=tot=;
scanf("%d",&n);
for (int i=;i<=n-;i++)
{
scanf("%d%d%d",&d[i][],&d[i][],&d[i][]);
add(d[i][],d[i][],d[i][]);
add(d[i][],d[i][],d[i][]);
}
dfs1();
dfs2(,);
for (int i=;i<=n-;i++)
{
if (depth[d[i][]]>depth[d[i][]]) swap(d[i][],d[i][]);//make the higher depth node to map the Edge
update(,,tot2,w[d[i][]],d[i][]); //change the value of the loc->w[d[i][1]]
}
}
inline int query(int u,int l,int r,int l1,int r1)
{
if (l1<=l&&r1>=r) return tree[u];
int mid=(l+r)>>;
if (r1<=mid) return query(L(u),l,mid,l1,r1);
else if (l1>mid) return query(R(u),mid+,r,l1,r1);
else {
return max(query(L(u),l,mid,l1,r1),query(R(u),mid+,r,l1,r1));
}
}
int findans(int va,int vb)
{
int f1,f2,ans;
f1=top[va];
f2=top[vb];
ans=;
while (f1!=f2)//find lca
{
if (depth[f1]<depth[f2])
{
swap(f1,f2);
swap(va,vb);
}
ans=max(ans,query(,,tot2,w[f1],w[va]));//swap make w[f1]<w[f2]
if (f1==f2) return ans;//in the same chain
va=fa[f1];f1=top[va];
}
if (va==vb) return ans;
if (depth[va]>depth[vb]) swap(va,vb);
return max(ans,query(,,tot2,w[son[va]],w[vb]));//the last do the f1=top[va]
}
void read()
{
ch[]='G';
scanf("%s",ch);
}
void work()
{
for (read();ch[]!='D';read())
{
int x,y;
scanf("%d%d",&x,&y);
if (ch[]=='Q') printf("%d\n",findans(x,y));
else update(,,tot2,w[d[x][]],y);
}
}
int main()
{
scanf("%d",&t);
for (int i=;i<=t;i++)
{
doit();
work();
}
}