线段树初步

该程序使用C++实现了一个线段树的数据结构,用于处理区间插入和查询问题。线段树的节点包含左右边界和标记值,通过递归建树实现区间覆盖。主要函数包括构建树、插入操作和查询区间长度。在主函数中,读取数据并进行多次插入,最后输出查询结果。
摘要由CSDN通过智能技术生成

 

Code:

#include <bits/stdc++.h>
#define Maxsize 60000
 
using namespace std;
 
//线段树节点
struct node
{
    int ld, rd; //左右孩子节点
    int key;    //标记值
} Tree[Maxsize * 2 + 1000];
 
//建树,i表示节点,a表示节点左右两边,从1开始建树
void buildtree(int i, int a, int b)
{
    Tree[i].ld = a;
    Tree[i].rd = b;
    if (b - a == 1)
        return;
    buildtree(i * 2, a, (a + b) / 2);
    buildtree(i * 2 + 1, (a + b) / 2, b);
    return;
}
 
//插入
void insert(int i, int a, int b)
{
    //没被完全覆盖
    if (Tree[i].key == 0)
    {
        int m = (Tree[i].ld + Tree[i].rd) / 2;
        //完全覆盖
        if ((a == Tree[i].ld) && (b == Tree[i].rd))
        {
            Tree[i].key = 1;
            return;
        }
        //如果在左子树
        else if (b <= m)
            insert(i * 2, a, b);
        //如果在右子树
        else if (a >= m)
            insert(i * 2 + 1, a, b);
        //如果横跨,则一分为二
        else
        {
            insert(i * 2, a, m);
            insert(i * 2 + 1, m, b);
        }
    }
}
 
//统计长度
int QLen(int i)
{
    if (Tree[i].key == 1)
        return Tree[i].rd - Tree[i].ld;
    else if (Tree[i].rd - Tree[i].ld == 1)
        return 0;
    else
        return QLen(i * 2) + QLen(i * 2 + 1);
}
 
int main()
{
    int n;
    while (cin >> n)
    {
        buildtree(1, 1, Maxsize);
        int a, b;
        for (int i = 0; i < n; i++)
        {
            cin >> a >> b;
            insert(1, a, b);
        }
        cout << QLen(1);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值