洛谷 P4114 Qtree1(树链剖分+树状数组)

P4114 Qtree1

思路:

树剖后,对于一条边来说,把边权赋给儿子节点,然后树状数组更新,求区间最大值。

代码:

#include<bits/stdc++.h>
using namespace std;
const int N=100005;
struct edge
{
	int to,cost;
};
struct Edge
{
	int u,v,w;
};
vector<Edge> e;
int son[N];//son[i]表示i的重儿子
int size[N];//size[i]表示i为根包含自己的字数节点个数
int f[N];//f[i]表示i的父亲
int dep[N];//dep[i]表示i的深度
vector<edge> G[N];
int c[N],a[N];
int n;
int lowbit(int x)
{
	return x & (-x);
}
void updata(int x)
{
	int lx, i;
	while (x <= n)
	{
		c[x] = a[x];
		lx = lowbit(x);
		for (i=1; i<lx; i<<=1)
			c[x] = max(c[x], c[x-i]);
		x += lowbit(x);
	}		
}
int query(int x, int y)
{
	int ans = 0;
	while (y >= x)
	{
		ans = max(a[y], ans);
		y --;
		for (; y-lowbit(y) >= x; y -= lowbit(y))
			ans = max(c[y], ans);
	}
	return ans;
}
void addedge(int u,int v,int w)
{
    G[u].push_back({v,w});
    G[v].push_back({u,w});
}
void dfs1(int cur,int fa)
{
	size[cur]=1;
	for(int i=0;i<G[cur].size();i++)
	{
		int to=G[cur][i].to;
		if(to==fa) continue;
		dep[to]=dep[cur]+1;
		f[to]=cur;
		dfs1(to,cur);
		size[cur]+=size[to];
		if(size[to]>size[son[cur]]) son[cur]=to;
	}
}
int top[N];//top[i]表示节点i所在链的顶端
int id[N];//id[i]表示i的新编号
int val[N];//val[i]表示新编号的点权
int cnt;
void dfs2(int cur,int t,int w)
{
	id[cur]=++cnt;
	val[cnt]=w;
	a[cnt]=w;
	updata(cnt);
	top[cur]=t;
	if(son[cur])
	{
		for(int i=0;i<G[cur].size();i++)
			if(G[cur][i].to==son[cur])
			{
				dfs2(son[cur],t,G[cur][i].cost);
				break;
			}
	}
	for(int i=0;i<G[cur].size();i++)
		if(G[cur][i].to!=f[cur]&&G[cur][i].to!=son[cur])
			dfs2(G[cur][i].to,G[cur][i].to,G[cur][i].cost);
}
int query_max(int x, int y)
{
    int ans = 0, fx = top[x], fy = top[y];
    while (fx != fy)
    {
        if (dep[fx] < dep[fy]) swap(x, y), swap(fx, fy);
        ans=max(ans,query(id[fx],id[x]));
        x = f[fx], fx = top[x];
    }
    if (id[x] > id[y]) swap(x, y);
    ans=max(ans,query(id[x]+1,id[y]));
    return ans;
}
void init()
{
    cnt=0;
    memset(son,0,sizeof(son));
    memset(size,0,sizeof(size));
    memset(f,0,sizeof(f));
    memset(dep,0,sizeof(dep));
    memset(a, 0, sizeof(a));
    memset(c,0,sizeof(c));
    for(int i=1;i<=n;i++) G[i].clear();
}
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin>>n;
	init();
	int u,v,w;
	for(int i=0;i<n-1;i++)
	{
		cin>>u>>v>>w;
		e.push_back({u,v,w});
		addedge(u,v,w);
	}
	f[1]=1;
    dfs1(1,1);
    dfs2(1,1,0);
    string flag;
    while(cin>>flag&&flag!="DONE")
    {
    	int x,y;
    	cin>>x>>y;
    	if(flag=="QUERY")
		{
			if(x==y) cout<<"0"<<endl;
			else cout<<query_max(x,y)<<endl;
		}
    	else
		{
			int temp=dep[e[x-1].u]>dep[e[x-1].v]?id[e[x-1].u]:id[e[x-1].v];
			a[temp]=y,updata(temp);
		}
    }
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值