线段树入门

POJ2777

count color
交了接近10次

  • 注意
  1. 颜色编号是从1开始的
  2. 区间关系可能是逆序的
  3. 染色是只能有一种颜色
#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;
}

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值