Count the Colors(线段树之区间成段更新)

来源:互联网 发布:linux sftp命令端口 编辑:程序博客网 时间:2024/05/01 22:57

萌萌哒的传送门


这道题目是线段树区间成段更新的应用,我们只需在建立线段树时从原来的左右儿子不相连,改为相连即可以解决此类问题.


如从原来的[l,mid] , [mid + 1,r] 改为 [l,mid],[mid,r]即可;


/********************* * zoj1610           * * 线段树的区间成段更新  * 延迟标记           * *********************/#include <iostream>#include <cstring>#include <cstdio>#include <cmath>#include <set>#include <queue>#include <vector>#include <cstdlib>#include <algorithm>#define ls u << 1#define rs u << 1 | 1#define lson l, mid, u << 1#define rson mid, r, u << 1 | 1#define INF 0x3f3f3f3fusing namespace std;typedef long long ll;const int M = 8800;int tmp[M << 2],a[M],to;/* * 线段树的区间更新,需要注意此时的区间不再是点的更新,所以 * 以[l,mid],[mid,r]来作为根的左右儿子,可以处理整段区间问题; */struct Node {    int u,v,c;    void read() {        scanf("%d %d %d",&u,&v,&c);    }} p[M];struct Color{ //用来保存最后状态的区间染色情况;    int l,r,c;}color[M];void pushdown(int u) {    if(tmp[u] != -1) {        tmp[ls] = tmp[rs] = tmp[u];        tmp[u] = -1;    }}void pushup(int u) {    if(tmp[ls] == tmp[rs])        tmp[u] = tmp[ls];}void update(int L,int R,int c,int l,int r,int u) {    int mid = (l + r) >> 1;    if(L <= l && R >= r) {        tmp[u] = c;    } else {        pushdown(u);        if(L < mid) update(L,R,c,lson);        if(R > mid) update(L,R,c,rson);        pushup(u);    }}void query(int l,int r,int u) {    int mid = (l + r) >> 1;    if(tmp[u] != -1) {        color[to].l = l;        color[to].r = r;        color[to++].c = tmp[u];    } else {        if(l == r - 1) return ;        query(lson);        query(rson);    }}int main() {    //freopen("in","r",stdin);    int n;    while(~scanf("%d",&n)) {        memset(tmp,-1,sizeof(tmp));        memset(a,0,sizeof(a));        int L = M, R = -1,num = 0;        for(int i = 0; i < n; i++) {            p[i].read();            L = min(L,p[i].u);            R = max(R,p[i].v);        }        for(int i = 0; i < n; i++) {            update(p[i].u,p[i].v,p[i].c,L,R,1);        }        to = 0;        query(L,R,1);        a[color[0].c]++;        for(int i = 1; i < to; i++){            if(color[i].l == color[i - 1].r && color[i].c == color[i - 1].c){                //如果当前区间是衔接之间的区间且颜色又一致的话,则这两段区间同属一段;                continue;            }            a[color[i].c]++; //否则为新的一段区间        }        for(int i = 0; i < M; i++){            if(a[i]){                printf("%d %d\n",i,a[i]);            }        }        puts("");    }    return 0;}


0 0