POJ - 2777 - Count Color(线段树)

题目链接:https://vjudge.net/problem/POJ-2777

题目大意:给你一个长度为l的木板,有两个操作,一个是将一个区间染色,一个是询问区间有多少种颜色

  很显然的线段树裸题,但是统计区间的颜色种类确实是一个难点,因为颜色很少,最多也就30种,所以我们可以用二进制位来存储这种颜色,每一位的1代表存在这种颜色,0代表不存在,那么我们区间内的颜色种类就是二进制数中1的数量了

#include<set>
#include<map>
#include<stack>
#include<queue>
#include<cmath>
#include<cstdio>
#include<cctype>
#include<string>
#include<vector>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define endl '\n'
#define rtl rt<<1
#define rtr rt<<1|1
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define maxx(a, b) (a > b ? a : b)
#define minn(a, b) (a < b ? a : b)
#define zero(a) memset(a, 0, sizeof(a))
#define INF(a) memset(a, 0x3f, sizeof(a))
#define IOS ios::sync_with_stdio(false)
#define _test printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> P2;
const double pi = acos(-1.0);
const double eps = 1e-7;
const ll MOD =  1000000007LL;
const int INF = 0x3f3f3f3f;
const int _NAN = -0x3f3f3f3f;
const double EULC = 0.5772156649015328;
const int NIL = -1;
template<typename T> void read(T &x){
    x = 0;char ch = getchar();ll f = 1;
    while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
    while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
const int maxn = 1e5+10;
int sum[maxn<<2], add[maxn<<2];
inline void push_up(int rt) {
    sum[rt] = sum[rtl]|sum[rtr];
}
inline void push_down(int rt) {
    if (add[rt]) {
        add[rtl] = add[rtr] = add[rt];
        sum[rtl] = sum[rtr] = add[rt];
        add[rt] = 0;
    }
}
void build(int rt, int l, int r) {
    if(l==r) {
        sum[rt] = 1;
        return;
    }
    int mid = (l+r)>>1;
    build(lson);
    build(rson);
    push_up(rt);
}
void update(int a, int b, int c, int rt, int l, int r) {
    if (a<=l && b>=r) {
        add[rt] = 1<<c;
        sum[rt] = 1<<c;
        return;
    }
    push_down(rt);
    int mid = (l+r)>>1;
    if (a<=mid)
        update(a, b, c, lson);
    if (b>mid)
        update(a, b, c, rson);
    push_up(rt);
}
int query(int a, int b, int rt, int l, int r) {
    if (a<=l && b>=r)
        return sum[rt];
    push_down(rt);
    int mid = (l+r)>>1, ans = 0;
    if (a<=mid)
        ans |= query(a, b, lson);
    if (b>mid)
        ans |= query(a, b, rson);
    return ans;
}
int main(void) {
    int l, t, o;
    scanf("%d%d%d", &l, &t, &o);
    build(1, 1, l);
    while(o--) {
        char od[3]; int a, b;
        scanf("%s%d%d", od, &a, &b);
        if (a>b) swap(a, b);
        if (od[0] == 'P')
            printf("%d\n", __builtin_popcount(query(a, b, 1, 1, l)));
        else {
            int c;
            scanf("%d", &c);
            update(a, b, c-1, 1, 1, l);
        }
    }
    return 0;
}

 

posted @ 2020-03-13 13:52  shuitiangong  阅读(135)  评论(0编辑  收藏  举报