poj 2777 Count Color

http://poj.org/problem?id=2777

  简单线段树,【成段更新,成段查询】!

View Code
  1 #include <cstdio>
  2 #include <cstring>
  3 #include <cstdlib>
  4 #include <algorithm>
  5 
  6 using namespace std;
  7 
  8 #define lson l, m, rt << 1
  9 #define rson m + 1, r, rt << 1 | 1
 10 
 11 const int maxn = 100001;
 12 int color[maxn << 2], late[maxn << 2];
 13 
 14 void up(int rt) {
 15     color[rt] = color[rt << 1] | color[rt << 1 | 1];
 16 }
 17 
 18 void down(int rt) {
 19     int l = rt << 1, r = rt << 1 | 1;
 20 
 21     if (late[rt]) {
 22         late[l] = late[r] = late[rt];
 23         color[l] = color[r] = late[rt];
 24         late[rt] = 0;
 25     }
 26 }
 27 
 28 void build(int l, int r, int rt) {
 29     late[rt] = 0;
 30     if (l == r) {
 31         color[rt] = 2;
 32 
 33         return ;
 34     }
 35     int m = (l + r) >> 1;
 36 
 37     build(lson);
 38     build(rson);
 39     up(rt);
 40 }
 41 
 42 void update(int key, int L, int R, int l, int r, int rt) {
 43     if (L <= l && r <= R) {
 44         color[rt] = late[rt] = 1 << key;
 45 
 46         return ;
 47     }
 48     int m = (l + r) >> 1;
 49 
 50     down(rt);
 51     if (L <= m) update(key, L, R, lson);
 52     if (m < R) update(key, L, R, rson);
 53     up(rt);
 54 }
 55 
 56 int query(int L, int R, int l, int r, int rt) {
 57     if (L <= l && r <= R) {
 58         return color[rt];
 59     }
 60     int m = (l + r) >> 1;
 61     int ret = 0;
 62 
 63     down(rt);
 64     if (L <= m) ret |= query(L, R, lson);
 65     if (m < R) ret |= query(L, R, rson);
 66     up(rt);
 67 
 68     return ret;
 69 }
 70 
 71 int main() {
 72     int l, t, o;
 73     int a, b, c;
 74     char op[3];
 75 
 76     freopen("in", "r", stdin);
 77     while (~scanf("%d%d%d", &l, &t, &o)) {
 78         build(1, l, 1);
 79         while (o--) {
 80             scanf("%s", op);
 81             switch (op[0]) {
 82                 case 'C':
 83                     scanf("%d%d%d", &a, &b, &c);
 84                     if (a > b) {
 85                         a ^= b;
 86                         b ^= a;
 87                         a ^= b;
 88                     }
 89                     update(c, a, b, 1, l, 1);
 90 
 91                     break;
 92                 case 'P':
 93                     scanf("%d%d", &a, &b);
 94                     if (a > b) {
 95                         a ^= b;
 96                         b ^= a;
 97                         a ^= b;
 98                     }
 99                     c = query(a, b, 1, l, 1);
100 
101                     int cnt = 0;
102 
103                     while (c) {
104                         cnt += c & 1;
105                         c >>= 1;
106                     }
107                     printf("%d\n", cnt);
108 
109                     break;
110             }
111         }
112     }
113 
114     return 0;
115 }

——written by Lyon

原文地址:https://www.cnblogs.com/LyonLys/p/poj_2777_Lyon.html