//
// main.cpp
// Richard
//
// Created by 邵金杰 on 16/9/22.
// Copyright © 2016年 邵金杰. All rights reserved.
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1000000+100;
const int inf=99999999;
struct edge{
int v,w,next;
}edge[maxn*3];
int e[maxn][3];
int n;
int cnt,tot;
int head[maxn];
int siz[maxn],son[maxn],fa[maxn],ti[maxn],top[maxn],dep[maxn];
void add_edge(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
//dfs序为线段树做准备
void dfs_1(int u,int f,int d)
{
son[u]=0;
fa[u]=f;
siz[u]=1;
dep[u]=d;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==f) continue;
dfs_1(v,u,d+1);
siz[u]+=siz[v];
if(siz[v]>siz[son[u]]) son[u]=v;
}
}
void dfs_2(int u,int tp)
{
ti[u]=++tot;top[u]=tp;
if(son[u]!=0) dfs_2(son[u],tp);
for(int i=head[u];i!=-1;i=edge[i].next)
if(edge[i].v!=fa[u]&&edge[i].v!=son[u])
dfs_2(edge[i].v,edge[i].v);
}
//线段树
struct node{
int l,r,val,max;
int mid(){return (l+r)>>1;}
}tree[maxn*4];
void build_tree(int pos,int l,int r)
{
tree[pos].l=l;tree[pos].r=r;tree[pos].val=tree[pos].max=-inf;
if(l==r) return ;
int mid=tree[pos].mid();
build_tree(pos*2,l,mid);
build_tree(pos*2+1,mid+1,r);
}
void updata(int pos,int id,int w)
{
if(tree[pos].l==tree[pos].r)
{
tree[pos].val=tree[pos].max=w;
return ;
}
int mid=tree[pos].mid();
if(id<=mid) updata(pos*2,id,w);
else updata(pos*2+1,id,w);
tree[pos].max=max(tree[pos*2].max,tree[pos*2+1].max);
}
int query(int pos,int l,int r)
{
int ans=-inf;
if(tree[pos].l>=l&&tree[pos].r<=r)
return tree[pos].max;
int mid=tree[pos].mid();
if(l<=mid) ans=max(ans,query(pos*2,l,r));
if(r>mid) ans=max(ans,query(pos*2+1,l,r));
return ans;
}
int lca(int x,int y)
{
int ans=-inf;
while(top[x]!=top[y])
{
if(dep[top[x]]<dep[top[y]]) swap(x,y);
ans=max(ans,query(1,ti[top[x]],ti[x]));
x=fa[top[x]];
}
if(dep[x]<dep[y]) swap(x,y);
if(x!=y) ans=max(ans,query(1,ti[y]+1,ti[x]));
return ans;
}
void intial()
{
cnt=0,tot=0;
memset(head,-1,sizeof(head));
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
intial();
scanf("%d",&n);
for(int i=1;i<n;i++) {
scanf("%d%d%d",&e[i][0],&e[i][1],&e[i][2]);
add_edge(e[i][0],e[i][1],e[i][2]);
add_edge(e[i][1],e[i][0],e[i][2]);
}
dfs_1(1,1,1);
dfs_2(1,1);
build_tree(1,2,n);
for(int i=1;i<n;i++)
{
if(dep[e[i][0]]<dep[e[i][1]]) swap(e[i][0],e[i][1]);
updata(1,ti[e[i][0]],e[i][2]);
}
char cmd[100];
while(scanf("%s",cmd))
{
if(cmd[0]=='D') break;
if(cmd[0]=='C'){
int x,y;
scanf("%d%d",&x,&y);
updata(1,ti[e[x][0]],y);
}
else{
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",lca(x,y));
}
}
printf("\n");
}
return 0;
}
SPOJ Query on a tree(dfs序+树链剖分)
最新推荐文章于 2019-07-30 16:16:02 发布