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

hdu 1698 Just a Hook 线段树成段更新

时间:2017-08-23 16:21:18      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:print   ace   ota   结果   const   表示   return语句   nbsp   space   

线段树功能:update:成段替换

成段更新去要用到延迟标记,具体调试代码就容易懂些

#include <iostream>
#include <string>
#include <cstdio>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;

const int MAXN = 111111;
int sum[MAXN<<2], chg[MAXN<<2];//sum表示区间和,chg数组:非0就需要将它的儿子更新,更新是在下一次查询更新

void push_up(int rt)
{
    sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}

void push_down(int rt, int len)
{
    if(chg[rt] == 0) return;
    chg[rt<<1] = chg[rt<<1|1] = chg[rt];
    sum[rt<<1] = (len - (len >> 1)) * chg[rt];
    sum[rt<<1|1] = (len >> 1) * chg[rt];
    chg[rt] = 0;
}

void build(int l, int r, int rt)
{
    sum[rt] = 1;    //也可以写在return语句前,不影响结果
    chg[rt] = 0;
    if(l == r) return;
    int m = (l + r) >> 1;
    build(lson);
    build(rson);
    push_up(rt);
}

void update(int L, int R, int c, int l, int r, int rt)
{
    if(L <= l && r <= R)
    {
        sum[rt] = c * (r - l + 1);
        chg[rt] = c;
        return;
    }
    push_down(rt, r-l+1);
    int m = (l + r) >> 1;
    if(L <= m) update(L, R, c, lson);
    if(R > m) update(L, R, c, rson);
    push_up(rt);
}

int main()
{
    int T, Case = 0;
    scanf("%d", &T);
    while(T--)
    {
        int N, Q;
        scanf("%d%d", &N, &Q);
        build(1, N, 1);
        while(Q--)
        {
            int X, Y, Z;
            scanf("%d%d%d", &X, &Y, &Z);
            update(X, Y, Z, 1, N, 1);
        }
        printf("Case %d: The total value of the hook is %d.\n", ++Case, sum[1]);
    }
    return 0;
}

 

hdu 1698 Just a Hook 线段树成段更新

标签:print   ace   ota   结果   const   表示   return语句   nbsp   space   

原文地址:http://www.cnblogs.com/pach/p/7418703.html

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