P2094 运输

本文介绍了一种使用手写堆数据结构解决合并果子问题(P1090)的方法。通过每次找到并合并堆中最小的两个元素,然后将结果重新插入堆中,直至堆中只剩下一个元素。这种方法适用于需要不断寻找并合并最小元素的问题场景。

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

题目链接

这题就是合并果子(P1090)的翻版

每次找到最小的两个合并起来。用堆实现,这里用的是手写堆

代码:

// luogu-judger-enable-o2
#include<bits/stdc++.h>

using namespace std;

const int maxn=10000+10;
int n,k,heap[maxn],size=0;

void up(int p) 
{
    while(p>1)
    {
        if(heap[p]>heap[p/2])
        {
            swap(heap[p],heap[p/2]);
            p/=2;
        }
        else break;
    }
}
void insert(int val) 
{
    heap[++size]=val;
    up(size);
}//插入
void down(int p) 
{
    int s=p*2;
    while(s<=size)
    {
        if(s<size&&heap[s+1]>heap[s]) s++; 
        if(heap[s]>heap[p])
        {
            swap(heap[s],heap[p]);
            p=s; s=p*2;
        }
        else break;
    }
}
void extract() 
{
    heap[1]=heap[size--]; 
    down(1);
}//删除
int gettop() 
{
    return heap[1];
}//取堆顶
int main()
{
    cin>>n>>k;
    for(int i=1;i<=n;i++)
    {
        int a; 
        cin>>a;
        insert(a); 
    }
    while(size>=2)//如果堆里还有两个可取的数
    {
        int top1=gettop();extract();
        int top2=gettop();extract();//每次取出最小的
        insert((top1+top2)/k); 
    }
    cout<<gettop()<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/Robin20050901/p/10679678.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值