POJ2777
count color
交了接近10次
- 注意
- 颜色编号是从1开始的
- 区间关系可能是逆序的
- 染色是只能有一种颜色
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include <iostream>
using namespace std;
const int M = 1e5+10;
typedef long long LL;
LL a[M];
struct Node
{
/*当前下标覆盖的左右边界,这个边界总是比函数中的l和r范围大的*/
int ll;
int rr;
int color;
int tag;
}tree[4*M];
void pushup(int idx){
// 使用状态压缩,把30中颜色,压缩成一个整数,每个bit位表示该位是否有颜色
tree[idx].color = tree[idx<<1].color | tree[idx<<1|1].color;
}
int bitcnt(int x){
int cnt = 0;
while(x > 0) {
x -= (x&(-x));
cnt++;
}
return cnt;
}
void build(int L, int R, int idx){
tree[idx].ll = L, tree[idx].rr = R;
if(L == R){
tree[idx].color = 1; // 表示0号位有颜色
tree[idx].tag = 0;
return;
}
int mid = L + R >> 1;
build(L, mid, idx<<1);
build(mid+1, R, idx<<1|1);
// 用儿子更新当前
pushup(idx);
}
void pushdown(int u) {
if(tree[u].tag==0) return;
tree[u<<1].tag = tree[u<<1|1].tag = tree[u<<1].color = tree[u<<1|1].color = tree[u].tag;
tree[u].tag = 0;
}
void update(int L, int R, int add, int idx) {
if(tree[idx].ll == L && tree[idx].rr == R){
tree[idx].tag = tree[idx].color = add;
return;
}
pushdown(idx);
int mid = (tree[idx].ll + tree[idx].rr) >> 1;
if(R <= mid) update(L, R, add, idx<<1);
else if(L > mid) update(L, R, add, idx<<1|1);
else{
update(L, mid, add, idx<<1);
update(mid+1, R, add, idx<<1|1);
}
// 使用儿子更新当前
pushup(idx);
}
int query(int L, int R, int idx) {
if(tree[idx].ll == L && tree[idx].rr == R) return tree[idx].color;
pushdown(idx);
int mid = (tree[idx].ll + tree[idx].rr) >> 1;
if(R <= mid) return query(L, R, idx<<1);
else if(L > mid) return query(L, R, idx<<1|1);
else{
return query(L, mid, idx<<1) | query(mid+1, R, idx<<1|1);
}
}
int main(){
int l, t, o;
scanf("%d%d%d", &l, &t, &o);
build(1,l, 1);
while(o--){
char op[2];
int l, r, color;
scanf("%s %d %d", op, &l, &r);
if(op[0]=='C'){
scanf("%d", &color);
if (l > r) {
swap(l, r);
}
color--;
color = (1<<color);
update(l, r, color, 1);
}else{
if (l > r) {
swap(l, r);
}
int ans = query(l, r, 1);
printf("%d\n", bitcnt(ans));
}
}
return 0;
}