hdu 1698 Just A Hook 线段树的一道题

关于线段树以前也有过接触,不过忘了,重新回顾一下,线段树是用二叉树来实现的。

关于线段树的概念,这个blog写的很详细,大家可以看一下http://www.cnblogs.com/shuaiwhu/archive/2012/04/22/2464583.html

hdu 1698 Just A Hook

这题题意是屠夫的钩子为n的长度,每段的材质都可以改变,一开始都是铜材质的,经过q次变化后求钩子的价值。(1表示铜,2表示银,3表示金)我们可以把这题简化成染色问题,给钩子染色,一开始都是1这种颜色,然后用别的颜色覆盖上去,这样比较好理解。一题比较基础的线段树,也不多说,附上代码:

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
const int MAXN=400012;
class node{
    public:
    int left,right,value;
} a[MAXN];
int maxroot,n,q,i;
int max(int a,int b)
{
    if (a>b) return a; else return b;
}
void build(int root,int l,int r)//建树
{
   int mid; mid=(l+r)>>1;
   maxroot=max(root,maxroot);
   a[root].left=l;
   a[root].right=r;
   a[root].value=1;
   if (l==r) return;
   build(root*2,l,mid);
   build(root*2+1,mid+1,r);

}
void color(int root,int l,int r,int v)//染色,可以说这是用了线段树中的Lazy算法吧
{
    if (l<=a[root].left&&a[root].right<=r)
    {
        a[root].value=v;
    }
    else{
        if (a[root].value!=-1) a[root*2].value=a[root*2+1].value=a[root].value;
        a[root].value=-1;
        if (l<=a[root*2].right) color(root*2,l,r,v);
        if (a[root*2+1].left<=r) color(root*2+1,l,r,v);
    }
}
int  Count(int root)//计算
{
    if (root<=maxroot)
    {
        if (a[root].value!=-1) return a[root].value*(a[root].right-a[root].left+1);
        else return Count(root*2)+Count(root*2+1);
    } else return 0;
}
int main()
{
    int T,x,y,v;
    cin>>T;
    for (int I=1;I<=T;I++)
    {
        scanf("%d",&n);
        scanf("%d",&q);
        maxroot=1;
        build(1,1,n);
        for (i=1;i<=q;i++)
        {
            scanf("%d%d%d",&x,&y,&v);
            color(1,x,y,v);
        }
        cout<<"Case "<<I<<": The total value of the hook is "<<Count(1)<<'.'<<endl;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值