洛谷P3378 二叉堆模板

本文深入探讨了小根堆这一高效数据结构的性质及其实现。详细介绍了小根堆的三种基本操作:添加元素、查询根顶元素、删除根节点,并通过具体代码示例展示了如何在C++中实现这些操作。适用于对数据结构和算法有需求的学习者和开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小根堆性质: 左儿子=>根节点<=右儿子

三个操作:1.添加x O(logn)  2.查询根顶O(1)   3.删除根节点  O(logn)

添加:末尾先加x,然后不断与更小的上移(交换)

删除:先将点1跟k交换,然后点1不断下移(交换),跟更小的儿子交换

保持性质不变

//luoguP3378 小根堆模板
#include<stdio.h>
#include<math.h>
#include<iostream>
#include<string.h>
using namespace std;
#define ll long long

namespace Heap{

    int h[1000005];int k=0;
    void add(int x){
        h[++k]=x;
        int y=k;
        while(y>1&&h[y/2]>h[y]){
            swap(h[y/2],h[y]);
            y=y/2;
        }
    }
    int get(){
        return h[1];
    }
    void pop(){
        swap(h[1],h[k]);--k;
        int x=1,y=2;
        while((y<=k&&h[y]<h[x])||(y+1<=k&&h[y+1]<h[x])){
            if(y+1<=k&&h[y]>h[y+1])y++;//选y还是y+1
            swap(h[x],h[y]);
            x=y;y*=2;
        }
    }
}


int main(){

    int n;cin>>n;
    while(n--){
        int t;cin>>t;
        if(t==1){
            int x;cin>>x;
            Heap::add(x);
        }
        if(t==2){
            cout<<Heap::get()<<endl;
        }
        if(t==3){
            Heap::pop();
        }
    }


    system("pause");
    return 0;
}

 

### 关于 P10466 邻值查找问题的二叉查找树解决方案分析 #### 一、背景介绍 在处理邻值查找问题时,二叉查找树(BST, Binary Search Tree)是一种有效的数据结构。通过构建并维护一棵平衡的二叉查找树,可以实现高效的插入、删除以及查询操作。 #### 二、具体应用到题目中的策略 针对该类问题,在构建二叉查找树的过程中需要注意节点的选择方式及其比较逻辑。当涉及到数值大小关系判断时,应确保遵循左子树小于根节点而右子树大于等于根节点的原则[^1]。这有助于保持树形结构稳定有序,从而支持快速定位目标元素或其最近邻居。 #### 三、代码示例 下面给出一段基于Python语言编写的简单版本二叉查找树实现: ```python class TreeNode: def __init__(self, key=None): self.key = key self.left = None self.right = None def insert(root, value): if root is None: return TreeNode(value) if value < root.key: root.left = insert(root.left, value) elif value >= root.key: root.right = insert(root.right, value) return root def find_nearest_neighbor(root, target_value): current_node = root best_match = None while current_node is not None: if abs(target_value - (current_node.key or float('inf'))) < abs( target_value - (best_match.key if best_match else float('inf'))): best_match = current_node if target_value < current_node.key: current_node = current_node.left else: current_node = current_node.right return best_match and best_match.key # 构建测试用例 test_data_points = [5, 3, 7, 2, 4, 6, 8] bst_root = None for point in test_data_points: bst_root = insert(bst_root, point) print(find_nearest_neighbor(bst_root, 5)) ``` 此段程序展示了如何创建一个基本功能完整的二叉查找树,并提供了`find_nearest_neighbor()`函数用于执行邻近值搜索任务。值得注意的是,为了提高效率和稳定性,实际竞赛编程中可能会采用更复杂的自平衡机制如AVL树或是红黑树等变种形式来代替简单的二叉查找树。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值