hdu1698

本文介绍了一种使用C语言实现的段树数据结构。通过具体的代码示例,详细展示了如何构建段树、更新节点以及查询区间长度的方法。适用于需要高效处理区间操作的问题。
#include<stdio.h>
struct segtree
{
    int left,right;
    int length;
};

const int maxn=100000+5;
int n,q;
segtree tree[maxn*4];
int x,y,z;

void build(int low,int high,int index)
{
    tree[index].left=low;
    tree[index].right=high;
    tree[index].length=1;
    if(low==high)
    {
        return;
    }
    else
    {
        int mid=(low+high)/2;
        build(low,mid,index*2);
        build(mid+1,high,index*2+1);
    }
}

void update(int low,int high,int length,int index)
{
    if(tree[index].length==length||(tree[index].left==low&&tree[index].right==high))
    {
        tree[index].length=length;
        return ;
    }
    else
    {
        if(tree[index].length)
        {
            tree[index*2].length=tree[index].length;
            tree[index*2+1].length=tree[index].length;
            tree[index].length=0;
        }
        int mid=(tree[index].left+tree[index].right)/2;
        if(high<=mid)
            update(low,high,length,index*2);
        else if(low>mid)
            update(low,high,length,index*2+1);
        else
        {
            update(low,mid,length,index*2);
           update(mid+1,high,length,index*2+1);
        }
    }
}

int query(int low,int high,int index)
{
    int mid=(tree[index].left+tree[index].right)/2;
    if(tree[index].left==low&&tree[index].right==high)
        {
            if(tree[index].length)
              return tree[index].length*(high-low+1);
            else
                return query(low,mid,index*2)+query(mid+1,high,index*2+1);
        }
        else
        {
            if(high<=mid)
            return query(low,high,index*2);
        else if(low>mid)
            return query(low,mid,index*2+1);
        else
        {
            return query(low,mid,index*2)+query(mid+1,high,index*2+1);
        }
        }
}

int main()
{
    int t;
    while(scanf("%d",&t)!=EOF)
    {
        int kase=1;
        while(t--)
        {
          scanf("%d%d",&n,&q);
          build(1,n,1);
            while(q--)
             {
               scanf("%d%d%d",&x,&y,&z);
               update(x,y,z,1);
             }
        printf("Case %d: The total value of the hook is %d.\n",kase++,query(1,n,1));
        }
    }
    return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值