POJ 2777 Count Color(线段树)

POJ 2777 Count Color

题目链接

就一个线段树,颜色二进制表示就可以,成段更新成段查询延迟操作

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

#define lson(x) ((x<<1)+1)
#define rson(x) ((x<<1)+2)

const int N = 100005;

struct Node {
	int l, r, color, lazy;
} node[N * 4];

void pushup(int x) {
	node[x].color = node[lson(x)].color | node[rson(x)].color;
}

void pushdown(int x) {
	if (node[x].lazy) {
		node[lson(x)].color = node[x].lazy; node[lson(x)].lazy = node[x].lazy;
		node[rson(x)].color = node[x].lazy; node[rson(x)].lazy = node[x].lazy;
		node[x].lazy = 0;
	}
}

void build(int l, int r, int x = 0) {
	node[x].l = l; node[x].r = r; node[x].lazy = 0;
	if (l == r) {
		node[x].color = 1;
		return;
	}
	int mid = (l + r) / 2;
	build(l, mid, lson(x));
	build(mid + 1, r, rson(x));
	pushup(x);
}

void add(int l, int r, int c, int x = 0) {
	if (node[x].l >= l && node[x].r <= r) {
		node[x].color = (1<<(c - 1));
		node[x].lazy = (1<<(c - 1));
		return;
	}
	pushdown(x);
	int mid = (node[x].l + node[x].r) / 2;
	if (l <= mid) add(l, r, c, lson(x));
	if (r > mid) add(l, r, c, rson(x));
	pushup(x);
}

int query(int l, int r, int x = 0) {
	if (node[x].l >= l && node[x].r <= r)
		return node[x].color;
	int mid = (node[x].l + node[x].r) / 2;
	int ans = 0;
	pushdown(x);
	if (l <= mid) ans |= query(l, r, lson(x));
	if (r > mid) ans |= query(l, r, rson(x));
	pushup(x);
	return ans;
}

int bitcount(int x) {
	return x == 0 ? 0 : bitcount(x>>1) + (x&1);
}

int l, t, o;
char str[5];
int a, b, v;

int main() {
	while (~scanf("%d%d%d", &l, &t, &o)) {
		build(1, l);
		while (o--) {
			scanf("%s%d%d", str, &a, &b);
			if (a > b) swap(a, b);
			if (str[0] == 'C') {
				scanf("%d", &v);
				add(a, b, v);
			} else printf("%d\n", bitcount(query(a, b)));
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值