POJ 2777 count color(线段树,lazy标记)

本文介绍如何使用线段树进行区间更新和查询操作,包括推断子节点信息、区间更新策略及优化技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里有一个思想:我们在更新的时候不必要更新到叶子节点,只要更新到当前区间包含线段树区间即可。

设计一个标志位,更新到此。

A Simple Problem with Integers 也是一个类似的题目

设计两个函数

push_down 将结点信息传递到下层节点(inc, sub,)

push_up      将下层节点信息反馈到上层(max,min,count)


#include <map>
#include <set>
#include <queue>
#include <cmath>
#include <cmath>
#include <vector>
#include <bitset>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define inf 0x3fffffff
#define mid ((l+r)>>1)
#define LSON(x) (x) << 1
#define RSON(x) (x) << 1 | 1
#define mem(x) memset(x,0,sizeof(x))
#define max(a,b) ((a)>(b)?(a):(b))
const double eps=1e-6;
typedef unsigned __int64 ull;
vector< vector<int> > edge;
#define lson l, m, rt << 1  
#define rson m + 1, r, rt << 1 | 1  
const int maxn = 100010;
struct  
{
	int l,r,color;
	int lazy;
}tt[maxn<<2];

void push_up(int p)
{
	tt[p].color=tt[p<<1].color | tt[p<<1|1].color;
}
void push_down(int p)
{
	tt[p<<1].lazy=tt[p].lazy;
	tt[p<<1].color=tt[p].lazy;	
	tt[p<<1|1].lazy=tt[p].lazy;
	tt[p<<1|1].color=tt[p].lazy;	
	tt[p].lazy=0;
}

void build(int p,int l,int r)
{
	tt[p].l=l;tt[p].r=r;
	tt[p].color=1;tt[p].lazy=0;
	if(l==r)
		return;
	build(p<<1,l,mid);
	build(p<<1|1,mid+1,r);
}
void update(int p,int l,int r,int c)
{
	if(tt[p].l>=l && tt[p].r<=r)
	{
		tt[p].color=c;
		tt[p].lazy=c;
		return;
	}
	if(tt[p].lazy)
		push_down(p);
	int m=(tt[p].l+tt[p].r)>>1;
	if(r<=m) update(p<<1,l,r,c);
	else if(l>m) update(p<<1|1,l,r,c);
	else
	{
		update(p<<1,l,m,c);
		update(p<<1|1,m+1,r,c);
	}
	push_up(p);
}

int query(int p,int l,int r)
{
	if(tt[p].l>=l && tt[p].r<=r)
		return tt[p].color;
	if(tt[p].lazy)
		push_down(p);
	int m=(tt[p].l+tt[p].r)>>1;
	int ans=0;
	if(r<=m) ans=query(p<<1,l,r);
	else if(l>m) ans=query(p<<1|1,l,r);
	else
	{
		ans=query(p<<1,l,m);
		ans|=query(p<<1|1,m+1,r);
	}
	push_up(p);
	return ans;
}
int getbit(int x)
{
	int i,ans=0;
	for(i=0;i<32;i++)
		if(   (  (1<<i) &  x )  )
			ans++;
	return ans;
}
int main()
{
	int L,T,O;
	int i,j,k;
	int A,B,C;
	char str[30];
	scanf("%d%d%d",&L,&T,&O);
	build(1,1,L);
	for(i=0;i<O;i++)
	{
		scanf("%s",str);
		if(str[0]=='C')
		{
			scanf("%d%d%d",&A,&B,&C);
			if(A>B)
			  swap(A,B);
			k=1<<(C-1);
			update(1,A,B,k);
			continue;
		}
		scanf("%d%d",&A,&B);
		if(A>B)
			  swap(A,B);
		k=query(1,A,B);
		k=getbit(k);
		printf("%d\n",k);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值