HDU 1698 Just a Hook(线段树)

本文深入探讨了区间替换与区间求和的高效实现策略,通过引入懒惰标记技术,显著提升了操作效率。文章引用了多个权威博客资源,并提供了实际AC代码,旨在帮助开发者理解并应用此技术于解决类似问题。

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1698

思路:updata()区间替换,query()区间求和

先上3篇博客 1:http://blog.sina.com.cn/s/blog_a2dce6b30101l8bi.html 

2:http://www.tuicool.com/articles/j6N3eaz 

3:http://www.cnblogs.com/Griselda/archive/2012/10/12/2721011.html

因为每次都更新到最下面会很费时间,所有有了懒惰标记

就是每次更新不更新到最后..而是更新到包含了区间的最大的节点.

然后如果下次更新的时候更新到了上次已经更新到的节点..

那先把上次更新暂停的节点往下更新..直到这次更新的区间最大的节点没有被标记..

因为没必要都更新只要更新到需要的程度就可以了(查询或者更新节点)

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>

const int inf = 0x3f3f3f3f;//1061109567
typedef long long ll;
const int maxn = 100010;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int sum[maxn<<2];
int value[maxn<<2];

void pushup(int rt)
{
    sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void pushdown(int rt,int m)
{
    if(value[rt])
    {
        value[rt<<1] = value[rt<<1|1] = value[rt];
        sum[rt<<1] = (m - (m>>1)) * value[rt];//左节点的数目总是比右节点的数目多一个或者相等
        sum[rt<<1|1] = (m>>1) * value[rt];
        value[rt] = 0;//增量已经传递了,所以要变为0
    }
}
void build(int l,int r,int rt)
{
    value[rt] = 0;
    sum[rt] = 1;
    if(l == r) return;
    int m = (l + r) >> 1;
    build(lson);
    build(rson);
    pushup(rt);
}
void updata(int L,int R,int c,int l,int r,int rt)
{
    if(l >= L && r <= R)
    {
        value[rt] = c;
        sum[rt] = (r - l + 1) * c;
        return;
    }
    pushdown(rt,r-l+1);//里面的参数要写对
    int m = (l + r) >> 1;
    if(L <= m) updata(L,R,c,lson);
    if(R > m) updata(L,R,c,rson);
    pushup(rt);
}
int main()
{
    int t,n,m;
    scanf("%d",&t);
    for(int cas=1; cas<=t; cas++)
    {
        scanf("%d%d",&n,&m);
        build(1,n,1);
        for(int i=0; i<m; i++)
        {
            int x,y,z;
            scanf("%d%d%d",&x,&y,&z);
            updata(x,y,z,1,n,1);
        }
        printf("Case %d: The total value of the hook is %d.\n",cas,sum[1]);
    }
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值