【洛谷P4116】Qtree3

题目描述:

给出N个点的一棵树(N-1条边),节点有白有黑,初始全为白

有两种操作:

0 i : 改变某点的颜色(原来是黑的变白,原来是白的变黑)

1 v : 询问1到v的路径上的第一个黑点,若无,输出-1

 

解析:

       树链剖分+线段树。

 

代码:
 

#include <bits/stdc++.h>
using namespace std;

const int Max=100005;
int n,m,s,tot,ans;
int first[Max],size[Max],son[Max],dep[Max],fa[Max];
int rev[Max],seg[Max],tree[Max<<2],top[Max];
struct shu{int to,next;};
shu edge[Max<<1];

inline int get_int()
{
	int x=0,f=1;
	char c;
	for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
	if(c=='-') f=-1,c=getchar();
	for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
	return x*f;
}
inline void print(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) print(x/10);
	putchar('0'+x%10);
}

inline void build(int x,int y)
{
	edge[++s].next=first[x];
	first[x]=s;
	edge[s].to=y;
}
inline void dfs1(int p)
{
	size[p]=1;
	for(int u=first[p];u;u=edge[u].next)
	{
	  int to=edge[u].to;
	  if(to==fa[p]) continue;
	  fa[to]=p,dep[to]=dep[p]+1,dfs1(to),size[p]+=size[to];
	  if(size[to]>size[son[p]]) son[p]=to;
	}
}
inline void dfs2(int p,int tp)
{
	top[p]=tp,seg[rev[p]=++tot]=p;
	if(!son[p]) return;
	dfs2(son[p],tp);
	for(int u=first[p];u;u=edge[u].next)
	{
	  int to=edge[u].to;
	  if(to==son[p]||to==fa[p]) continue;
	  dfs2(to,to);
	}
}

inline void update(int root){tree[root]=tree[root<<1]+tree[root<<1|1];}
inline void change(int root,int l,int r,int pos)
{
	if(l==r&&l==pos){tree[root]^=1;return;}
	int mid=(l+r)>>1;
	if(pos<=mid) change(root<<1,l,mid,pos);
	else change(root<<1|1,mid+1,r,pos);
	update(root);
}
inline int find(int root,int l,int r)
{
	if(l==r) return tree[root]?seg[l]:-1;
	int mid=(l+r)>>1;
	if(tree[root<<1]) return find(root<<1,l,mid);
	else if(tree[root<<1|1]) return find(root<<1|1,mid+1,r);
	else return -1;
}
inline int Q(int root,int l,int r,int L,int R)
{
	if(L<=l&&R>=r) return find(root,l,r);
	int mid=(l+r)>>1,ans=-1;
	if(L<=mid) ans=Q(root<<1,l,mid,L,R);
	if(~ans) return ans;
	if(R>mid) ans=Q(root<<1|1,mid+1,r,L,R);
	return ans;
}

inline int ask(int p)
{
	ans=-1;
	while(top[p]!=1)
	{
	  int x=Q(1,1,tot,rev[top[p]],rev[p]);
	  if(~x) ans=x;
	  p=fa[top[p]];
	}
	int x=Q(1,1,tot,rev[1],rev[p]);
	if(~x) ans=x;
	return ans;
}

int main()
{
	n=get_int(),m=get_int();
	for(int i=1;i<n;i++)
	{
	  int x=get_int(),y=get_int();
	  build(x,y),build(y,x);
	}
	dfs1(1),dfs2(1,1);
	while(m--)
	{
	  int tag=get_int(),x=get_int();
	  if(!tag) change(1,1,tot,rev[x]);
	  else print(ask(x)),putchar('\n');
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值