POJ 2777 Count Color 线段树区间更新位运算

题目链接

C A B C 是更新 A-B段位颜色C;

P A B    是查询 A - B 有种多少颜色;

居然把题目看成A不可能小于B。。。。(是有多渣T T)

因为只有30种颜色所以用int型可以记录下;

代码学着HH巨巨的 地址

#include<stdio.h>
#include<string.h>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mid (l+r)>>1
#define maxn 500000
int sum[maxn<<2],col[maxn<<2];
int num[34];
void pushup(int rt){//向上更新
	sum[rt]=sum[rt<<1]|sum[rt<<1|1];
}
void pushdown(int rt){
	if(col[rt]){//向下更新
		col[rt<<1]=col[rt<<1|1]=col[rt];
		sum[rt<<1]=sum[rt<<1|1]=sum[rt];
		col[rt]=0;
	}
}
void build(int l,int r,int rt)
{	
	sum[rt]=1;//初始为颜色1
	if(l==r){
		return;
	}
	int m=mid;
	build(lson);
	build(rson);
	pushup(rt);
}
void update(int L,int R,int c,int l,int r,int rt)
{
	if(L<=l&&r<=R)
	{
		sum[rt]=num[c];
		col[rt]=num[c];
		return;
	}
	pushdown(rt);
	int m=mid;
	if(L<=m) update(L,R,c,lson);
	if(R>m) update(L,R,c,rson);
	pushup(rt);
}
int query(int L,int R,int l,int r,int rt){
	if(L<=l&&R>=r){
		return sum[rt];
	}
	pushdown(rt);
	int m=mid;
	int res=0;
	if(L<=m) res=res|query(L,R,lson);
	if(R>m) res=res|query(L,R,rson);
	return res;
}
int main(){
	int n,q,t;
	memset(num,0,sizeof(num));
	num[1]=1;
	for(int i=2;i<=30;i++)//先储存每种颜色。。。
		num[i]=num[i-1]<<1;
	while(scanf("%d %d %d ",&n,&t,&q)!=EOF){
		memset(sum,0,sizeof(sum));
		memset(col,0,sizeof(col));
		build(1,n,1);
		while(q--)
		{
			char s[3];
            scanf("%s",s);
            int a,b,c; 
			scanf("%d%d",&a,&b);
			if(a>b){//万恶之源
				int x=a;
				a=b;
				b=x;
			}
			if(s[0]=='P')
			{
				int ans=0;
				int x=query(a,b,1,n,1);
				while(x)//统计颜色个数
				{
					if(x&1==1)
						ans++;
					x=x>>1;
				}
				printf("%d\n",ans);
			}
			else {
				scanf("%d",&c);
				update(a,b,c,1,n,1);
			}
		}
	}
	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值