洛谷 P4116 Qtree3(树链剖分+树状数组)

P4116 Qtree3

思路:

树链剖分+树状数组。对于白色,起始都赋值INF,对于反转,白色的我们反转黑色,即改变成它在树剖时的dfs序,黑色变白色就改成INF就行。这道题可以把1当做树根,每次查询1~u路径上第一个黑点就是深度最小的那个点,也就是dfs序最小的那个点。然后用树状数组查询区间最小值就行。

代码:

#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int N=1e5+5;
int a[N], c[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] = min(c[x], c[x-i]);
		x += lowbit(x);
	}		
}
int query(int x, int y)
{
	int ans = INF;
	while (y >= x)
	{
		ans = min(a[y], ans);
		y --;
		for (; y-lowbit(y) >= x; y -= lowbit(y))
			ans = min(c[y], ans);
	}
	return ans;
}
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<int> G[N];
void addedge(int u,int v)
{
    G[u].push_back(v);
    G[v].push_back(u);
}
void dfs1(int cur,int fa)
{
	size[cur]=1;
	for(int i=0;i<G[cur].size();i++)
	{
		int to=G[cur][i];
		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 res[N];
int cnt;
void dfs2(int cur,int t)
{
	id[cur]=++cnt;
	res[cnt]=cur;
	a[cnt]=INF;
	updata(cnt);
	top[cur]=t;
	if(son[cur]) dfs2(son[cur],t);
	for(int i=0;i<G[cur].size();i++)
		if(G[cur][i]!=f[cur]&&G[cur][i]!=son[cur])
			dfs2(G[cur][i],G[cur][i]);
}
void init()
{
    cnt=0;
    memset(son,0,sizeof(son));
    memset(size,0,sizeof(size));
    memset(f,0,sizeof(f));
    memset(dep,0,sizeof(dep));
    for(int i=1;i<=n;i++) G[i].clear();
}
int query_min(int x,int y)
{
	int ans = INF, fx = top[x], fy = top[y];
    while (fx != fy)
    {
        if (dep[fx] < dep[fy]) swap(x, y), swap(fx, fy);
        ans=min(query(id[fx],id[x]),ans);
        x = f[fx], fx = top[x];
    }
    if (id[x] > id[y]) swap(x, y);
    ans=min(ans,query(id[x],id[y]));
    return ans;
}
void update_node(int x)
{
	if(a[id[x]]==INF) a[id[x]]=id[x];
	else a[id[x]]=INF;
	updata(id[x]);
}
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int m,u,v;
	cin>>n>>m;
	init();
	for(int i=0;i<n-1;i++)
	{
		cin>>u>>v;
		addedge(u,v);
	}
	dfs1(1,1);
	dfs2(1,1);
	while(m--)
	{
		int x,y;
		cin>>x>>y;
		if(x)
		{
			int ans=query_min(1,y);
			if(ans==INF) cout<<"-1"<<endl;
			else cout<<res[ans]<<endl;
		}
		else
		{
			update_node(y);
		}
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值