数链剖分(Housewife Wind )

时间:2023-03-08 23:29:39
数链剖分(Housewife Wind )

 题目链接:https://vjudge.net/contest/279350#problem/B

题目大意:给你n,q,s。n指的是有n个点,q代表有q次询问,s代表的是起点。然后接下来会有n-1条边,双向边,带有权值,对于q次询问,如果输入的第一个数是1,然后接下来会输入两个数,t1,t2。t带边将第t1条边的权值改成t2.如果第一个数是0,接下来会输入一个t,询问从s到t的花费。

具体思路:对于边权,我们可以改成点权,这条边的权值赋给这条边上深度大的那条边,然后就是单点更新和区间查询了。

AC代码:

 #include<iostream>
#include<cmath>
#include<stack>
#include<queue>
#include<stdio.h>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
# define inf 0x3f3f3f3f
# define ll long long
# define lson l,m,rt<<
# define rson m+,r,rt<<|
const int maxn = 1e5+;
int sto[maxn],head[maxn],edgnum,dfsnum,depth[maxn];
int son[maxn],father[maxn],Size[maxn],ord[maxn],cost[maxn],top[maxn];
int tree[maxn<<];
struct node
{
int fr;
int to;
int nex;
int cost;
} edge[maxn<<],po[maxn<<];
void addedge(int fr,int to)
{
edge[edgnum].fr=fr;
edge[edgnum].to=to;
edge[edgnum].nex=head[fr];
head[fr]=edgnum++;
}
void dfs1(int fr,int rt,int dep)
{
father[fr]=rt;
Size[fr]=;
son[fr]=-;
depth[fr]=dep;
for(int i=head[fr]; i!=-; i=edge[i].nex)
{
int to=edge[i].to;
if(to==rt)
continue;
dfs1(to,fr,dep+);
Size[fr]+=Size[to];
if(son[to]==-||(Size[son[fr]]<Size[to]))
{
son[fr]=to;
}
}
}
void dfs2(int fr,int rt)
{
ord[fr]=++dfsnum;
cost[ord[fr]]=sto[fr];
top[fr]=rt;
if(son[fr]!=-)
dfs2(son[fr],rt);
for(int i=head[fr]; i!=-; i=edge[i].nex)
{
int u=edge[i].to;
if(son[fr]!=u&&father[fr]!=u)
{
dfs2(u,u);
}
}
}
void up(int rt)
{
tree[rt]=tree[rt<<]+tree[rt<<|];
}
void buildtree(int l,int r,int rt)
{
if(l==r)
{
tree[rt]=sto[l];
return ;
}
int m=(l+r)>>;
buildtree(lson);
buildtree(rson);
up(rt);
}
int query(int l,int r,int rt,int L,int R)
{
if(L<=l&&R>=r)
{
return tree[rt];
}
int ans=;
int m=(l+r)>>;
if(L<=m)
ans+=query(lson,L,R);
if(R>m)
ans+=query(rson,L,R);
up(rt);
return ans;
}
void update(int l,int r,int rt,int pos,int p)
{
if(l==r)
{
tree[rt]=p;
return ;
}
int m=(l+r)>>;
if(pos<=m)
update(lson,pos,p);
if(pos>m)
update(rson,pos,p);
up(rt);
}
int Query(int n,int x,int y)
{
int tx=top[x],ty=top[y];
int ans=;
while(tx!=ty)
{
if(depth[tx]<depth[ty])
{
swap(tx,ty);
swap(x,y);
}
ans+=query(,n,,ord[tx],ord[x]);
x=father[tx],tx=top[x];
}
if(depth[x]<depth[y])
{
swap(x,y);
}
return ans+query(,n,,ord[y]+,ord[x]);//这个地方注意应该是ord[y]+1,如果我们询问的是从3->5的,有可能3这个点是另一条边的权值,所以应该把点往下移动一个。
}
int main()
{
int n,q,s;
scanf("%d %d %d",&n,&q,&s);
int t1,t2,t3;
memset(head,-,sizeof(head));
for(int i=; i<=n-; i++)
{
scanf("%d %d %d",&t1,&t2,&t3);
addedge(t1,t2);
addedge(t2,t1);
po[i].fr=t1;
po[i].to=t2;
po[i].cost=t3;
}
dfs1(,-,);
dfs2(,);
for(int i=; i<=n-; i++)
{
t1=depth[po[i].fr];
t2=depth[po[i].to];
if(t1>t2)
{
swap(po[i].fr,po[i].to);
}
update(,n,,ord[po[i].to],po[i].cost);
}
while(q--)
{ scanf("%d",&t1);
if(t1==)
{
scanf("%d",&t2);
int ans=Query(n,s,t2);
printf("%d\n",ans);
s=t2;
}
else
{
scanf("%d %d",&t1,&t2);
update(,n,,ord[po[t1].to],t2);
}
}
return ;
}