权值线段树板子题

https://www.luogu.org/problem/P1168

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int tree[maxn*4];
int dtc[maxn];
int a[maxn];
void pushup(int root)
{
    tree[root]=tree[root<<1]+tree[root<<1|1];
}
void update(int root,int l,int r,int index) // 将权值线段树上值为index(已离散化)的位置值+1 
{
    if(l==r)
    {
        tree[root]++;
        return;
    }
    int mid=(l+r)/2;
    if(mid>=index)
        update(root<<1,l,mid,index);
    else
        update(root<<1|1,mid+1,r,index);
    pushup(root);
}
int querry(int root,int l,int r,int k) // 查询第k大的数字 
{
    if(l==r)
        return l;
    int mid=(l+r)/2;
    if(tree[root<<1]>=k)
        return querry(root<<1,l,mid,k);
    return querry(root<<1|1,mid+1,r,k-tree[root<<1]);
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%d",&a[i]);
        dtc[i]=a[i];
    }
    sort(a+1,a+1+n);
    int cnt=unique(a+1,a+1+n)-a-1;
    for(int i = 1; i <= n; ++i)
        dtc[i]=lower_bound(a+1,a+1+cnt,dtc[i])-a;
    for(int i = 1; i <= n; ++i)
    {
        update(1,1,n,dtc[i]);
        if(i&1)
        {
            int ans=querry(1,1,n,(i+1)/2);
            printf("%d\n",a[ans]);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
哈夫曼是一种带有权值的二叉,它的构造方法是通过贪心策略,将权值最小的两个节点合并成一个新节点,直到最后只剩下一个节点为止。下面是给定权值构造哈夫曼的详细步骤: 1. 将所有权值作为叶子节点,构造一个节点集合。 2. 从节点集合中选出两个权值最小的节点,合并成一个新节点,权值为两个节点的权值之和。 3. 将新节点加入节点集合中,并删除原来的两个节点。 4. 重复步骤2和3,直到节点集合中只剩下一个节点为止,这个节点就是哈夫曼的根节点。 下面是一个示例,假设给定的权值为[5, 9, 12, 13, 16, 45]: 首先构造出6个叶子节点: ``` 5 9 12 13 16 45 / / / / / / A B C D E F ``` 然后按照上面的步骤,合并权值最小的两个节点: ``` 5 9 12 13 16 45 / / / / / A B C D ┌────F │ 61 │ └────E ``` 继续合并权值最小的两个节点: ``` 5 9 12 13 16 45 / / / / / / A B C ┌────D E F │ 25 │ └─────┐ │ 36 │ └────C ``` 继续合并权值最小的两个节点: ``` 5 9 12 13 16 45 / / / / / / A B ┌─────┐ D E F │ │ 25 36 │ │ └─────┘ │ 61 │ └────C ``` 最后只剩下一个节点,它就是哈夫曼的根节点: ``` 111 / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ 5 106 / \ / \ / \ / \ / \ / \ A B C 61 / \ / \ D E ``` 因此,给定权值构造出的哈夫曼就是上面的形结构。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值