码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ - 1610 Count the Colors(线段树区间更新,单点查询)

时间:2015-11-12 11:23:57      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

1、给了每条线段的颜色,存在颜色覆盖,求表面上能够看到的颜色种类以及每种颜色的段数。

2、线段树区间更新,单点查询。

但是有点细节,比如:

输入:

2

0 1 1

2 3 1

输出:

1 2

这种情况就需要处理一下,代码中把所有的左端点都+1,避免了这种情况。

3、

技术分享
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

#define L(root) ((root) << 1)
#define R(root) (((root) << 1) + 1)

const int MAXN = 8005;

struct st
{
    // 区间范围
    int left, right;
    int flag;//-1没有颜色
} st[MAXN * 4];
int color[MAXN];//每种颜色看到的段数
// 建树代码基本不变
void build(int root, int l, int r)
{
    st[root].left = l, st[root].right = r, st[root].flag = -1;
    if (l == r)
    {
        return;
    }

    int m = l + ((r - l) >> 1);
    build(L(root), l, m);
    build(R(root), m + 1, r);
}

int query(int root, int x)//单点查询
{
    if (st[root].left == st[root].right)
    {
        return st[root].flag;
    }

    // 否则需将当前区间的“缓冲”值更新下去并修正各节点区间的总和
    if (st[root].flag!=-1)
    {
        st[L(root)].flag = st[root].flag;
        st[R(root)].flag = st[root].flag;
        st[root].flag = -1;
    }

    int m = st[root].left + ((st[root].right - st[root].left) >> 1);
    if (x <= m)
    {
        return query(L(root), x);
    }
    else
    {
        return query(R(root), x);
    }
}

void update(int root, int l, int r, int v)//区间更新
{
    // 如变更区间恰等于节点区间,只修正当前节点区间即可
    if (st[root].left == l && st[root].right == r)
    {
        st[root].flag = v;
        return;
    }

    // 否则需向下修正相关节点区间
    if (st[root].flag!=-1)
    {
        st[L(root)].flag = st[root].flag;
        st[R(root)].flag = st[root].flag;
        st[root].flag = -1;
    }

    int m = st[root].left + ((st[root].right - st[root].left) >> 1);
    if (r <= m)
    {
        update(L(root), l, r, v);
    }
    else if (l > m)
    {
        update(R(root), l, r, v);
    }
    else
    {
        update(L(root), l, m, v);
        update(R(root), m + 1, r, v);
    }
}

int main()
{
    int n,i;
    int x1,x2,c;
    int lastColor;//记录上一个颜色
    int nowColor;//当前颜色
    while(~scanf("%d",&n)){
        build(1,1,8001);
        for(i=1;i<=n;++i){
            scanf("%d%d%d",&x1,&x2,&c);
            update(1,++x1,x2,c);//++x1表示缩掉前面一点,处理了0 1 1,2 3 1这种情况,而且还符合了左端点从1开始
        }
        memset(color,0,sizeof(color));
        lastColor=-1;
        for(i=1;i<=8001;++i){
            nowColor=query(1,i);
            if(nowColor==lastColor)
                continue;
            else if(nowColor!=-1)
                ++color[nowColor];
            lastColor=nowColor;
        }
        for(i=0;i<=8001;++i)
            if(color[i])
                printf("%d %d\n",i,color[i]);
        printf("\n");
    }
    return 0;
}
View Code

 

ZOJ - 1610 Count the Colors(线段树区间更新,单点查询)

标签:

原文地址:http://www.cnblogs.com/bofengyu/p/4958290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!