题意:
给你一棵树,然后查询点u到v之间的最大值,并且中途可能会修改某个边的值
思路:
http://blog.sina.com.cn/s/blog_6974c8b20100zc61.html
↑这里树剖讲的很好
树剖基本题,没什么坑点但是写的时候,对于点的上下关系经常判断错,导致wa了一上午。树剖整体思路就是将树的边进行划分,最终达到类似倍增那样的不断跳跃来节省时间,同时把树按边转化为线性,这样就能用线段树维护了。
错误及反思:
刚刚学完去写了下模板题,发现树剖的代码量确实不小,感觉树剖和dfs序都是差不多一种东西,都是把树转化为线性结构,只不过一个的核心是点的处理,一个核心是边的处理
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N=20100;
pair<int,int> edge[N];
int segtree[N*4];
int depth[N],fa[N],son[N],top[N],si[N],id[N];
int n,tot,tid;
int first[N];
pair<int,pair<int,int> > b[N];
void addedge(int x,int y)
{
edge[tot].first=y;
edge[tot].second=first[x];
first[x]=tot++;
edge[tot].first=x;
edge[tot].second=first[y];
first[y]=tot++;
}
void dfs1(int now,int bef,int dep)
{
depth[now]=dep;
fa[now]=bef;
si[now]=1;
for(int i=first[now];i!=-1;i=edge[i].second)
{
if(edge[i].first!=bef)
{
dfs1(edge[i].first,now,dep+1);
si[now]+=si[edge[i].first];
if(son[now]==-1) son[now]=edge[i].first;
else son[now]=si[edge[i].first]>si[son[now]]?edge[i].first:son[now];
}
}
}
void dfs2(int now,int tp)
{
id[now]=tid++;
top[now]=tp;
if(son[now]!=-1) dfs2(son[now],tp);
for(int i=first[now];i!=-1;i=edge[i].second)
if(edge[i].first!=fa[now]&&edge[i].first!=son[now])
dfs2(edge[i].first,edge[i].first);
}
int findmax(int L,int R,int l,int r,int rt)
{
if(L<=l&&R>=r)
return segtree[rt];
int m=(l+r)/2;
int ans=0;
if(L<=m) ans=max(ans,findmax(L,R,lson));
if(R>m) ans=max(ans,findmax(L,R,rson));
return ans;
}
int query(int L,int R,int l,int r,int rt)
{
int fa1=top[L],fa2=top[R];
int ans=0;
while(fa1!=fa2)
{
if(depth[fa1]<depth[fa2])
{
swap(fa1,fa2);
swap(L,R);
}
ans=max(ans,findmax(id[fa1],id[L],0,tid-1,1));
L=fa[fa1];
fa1=top[L];
}
if(L==R) return ans;
if(depth[L]>depth[R]) swap(L,R);
ans=max(ans,findmax(id[son[L]],id[R],0,tid-1,1));
return ans;
}
void update(int pos,int val,int l,int r,int rt)
{
if(pos==l&&l==r)
{
segtree[rt]=val;
return ;
}
int m=(l+r)/2;
if(pos<=m) update(pos,val,lson);
else update(pos,val,rson);
segtree[rt]=max(segtree[rt<<1],segtree[rt<<1|1]);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(first,-1,sizeof(first));
memset(son,-1,sizeof(son));
scanf("%d",&n);
tot=0;tid=0;
for(int i=0;i<n-1;i++)
{
scanf("%d%d%d",&b[i].second.first,&b[i].second.second,&b[i].first);
addedge(b[i].second.first,b[i].second.second);
}
dfs1(1,1,1);
dfs2(1,1);
for(int i=0;i<n-1;i++)
{
if(depth[b[i].second.first]<depth[b[i].second.second]) swap(b[i].second.first,b[i].second.second);
update(id[b[i].second.first],b[i].first,0,tid-1,1);
}
while(1)
{
char temp[10];
int ta,tb;
scanf("%s",temp);
if(temp[0]=='D')
break;
else
{
scanf("%d%d",&ta,&tb);
if(temp[0]=='Q')
printf("%d\n",query(ta,tb,0,tid-1,1));
else
update(id[b[ta-1].second.first],tb,0,tid-1,1);
}
}
}
}