POJ 2777 Count Color(线段树、lazy思想)

大意是一块定长的木板,在上面涂颜色,每次涂一个区间,当询问某个区间时,要返回这个区间中的颜色数目。

这道题目其实和3468非常之像,也是要更新区间,也用到了lazy思想。可能略有不同的是,这道题目有个用到位运算的小技巧。由于总颜色数目较少(<= 30),一个区间上的颜色可以用一个32位的 int 表示,最后统计总颜色数时,只要运用或运算符(|)就可以。

#include<iostream>
#include<cstdio>
#define MID(x, y) ((x + y) >> 1)
#define R(x) (x << 1 | 1)
#define L(x) (x << 1)
using namespace std;


typedef struct{
	int l, r;
	long long board;
	long long c;
} NODE;

NODE st[440000];


void build(int t, int l, int r){
	st[t].l = l;
	st[t].r = r;
	st[t].c = 0;
	st[t].board = 1;
//	cout << "l--r: " << l <<" "<< r<< endl;
	if(l == r)
		return;
	else{
		build(L(t), l, MID(l, r));
		build(R(t), MID(l, r) + 1, r);
	}
}

void update(int t, int l, int r, int c){
	int mid = MID(st[t].l, st[t].r);
	//cout << t << l << r << c << endl;;
	if(st[t].l == l && st[t].r == r){
		st[t].board = 1;
		st[t].board = st[t].board << c - 1;
		st[t].c = c;
		return;
	}
	if(st[t].c != 0){
		st[L(t)].board = 1;
		st[L(t)].board = st[L(t)].board << st[t].c - 1;
		st[L(t)].c = st[t].c;
		st[R(t)].board = 1;
		st[R(t)].board = st[R(t)].board << st[t].c - 1;
		st[R(t)].c = st[t].c;
		st[t].c = 0;
	}
	
	if(r <= mid){
		update(L(t), l, r, c);
	}else if(l > mid){
		update(R(t), l, r, c);
	}else{
		update(L(t), l, mid, c);
		update(R(t), mid + 1, r, c);
	}
	st[t].board = (st[L(t)].board | st[R(t)].board);
//	cout << st[t].board << endl;
}

long long query(int t, int l, int r){
	int mid = MID(st[t].l, st[t].r);
	if(st[t].l == l && st[t].r == r){
		return st[t].board;
	}
	if(st[t].c != 0){
		st[L(t)].board = 1;
		st[L(t)].board = st[L(t)].board << st[t].c - 1;
		st[L(t)].c = st[t].c;
		st[R(t)].board = 1;
		st[R(t)].board = st[R(t)].board << st[t].c - 1;
		st[R(t)].c = st[t].c;
		st[t].c = 0;
	}

	if(r <= mid){
		return query(L(t), l, r);
	}else if(l > mid){
		return query(R(t), l, r);
	}else{
		return query(L(t), l, mid) | query(R(t), mid + 1, r);
	}
}


int count(long long a){
	int b = 0;
	while(a != 0){
		if(a % 2 == 1)
			b++;
		a = a >> 1;
	}
	return b;
}

int main(){
	int L, T, O;
	char cmd[10];
	scanf("%d %d %d", &L, &T, &O);
	build(1, 1, L);
	while(O--){
		scanf("%s", cmd);
		if(cmd[0] == 'C'){
			int x, y, z;
			scanf("%d %d %d", &x, &y, &z);
			if(y < x)
				swap(x, y);
			update(1, x, y, z);
		}else{
			int x, y;
			scanf("%d %d", &x, &y);
			if(y < x)
				swap(x, y);
			printf("%d\n", count(query(1, x, y)));
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值