合并果子

今天浅学了一下堆,发现这种东西简直就是为合并果子而生的啊!!!不仅风格上好看很多,而且很好理解啊!!而且c++模板库STL里面就只有堆的函数理解到了一点(蠢死了蠢死了

以下放原来用贪心的代码和用堆的进行对比:


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<ctime>
#include<iomanip>
#include<stack>
#include<climits>
#include<ctype.h>
using namespace std;
int b[30005],a[30005],n;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
      scanf("%d",a+i);
    sort(a+1,a+n+1);
    int ans=0,t,m=0,i=1,j=1;
    for(int k=1;k<=n-1;k++){//贪心,其实每次都要反复理解,要不然很容易就忘了
        if(m<j||i<=n&&a[i]<b[j])
          t=a[i++];
        else
          t=b[j++];
        if(m<j||i<=n&&a[i]<b[j])
          t+=a[i++];
        else
          t+=b[j++];
        ans+=t;
        b[++m]=t;
    }
    cout<<ans;
    return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctime>
#include<cctype>
#include<vector>
using namespace std;

int heap_size,n;

int heap[30001];

void put(int d)
{
    heap[++heap_size]=d;
    push_heap(heap+1,heap+heap_size+1,greater<int>());//STL
}

int get()
{
    pop_heap(heap+1,heap+heap_size+1,greater<int>());
    return heap[heap_size--];
}

void work()
{
    int x,y,ans=0;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>x;
        put(x);
    }
    for(int i=1;i<n;i++){
        x=get();//每次取两个小的合并
        y=get();
        ans+=x+y;
        put(x+y);//将合并后的插入小根堆
    }
    cout<<ans<<endl;
}

int main()
{
    ios::sync_with_stdio(0);//读入优化
    work();
    return 0;
}

继续努力。

### 关于蓝桥杯竞赛中的“合并果子”问题 #### 问题描述 在“合并果子”的问题中,给定若干果子,每果子有一定的重量。可以通过不断将两果子合并成一来减少果子的数量,直到最终只剩下一为止。每次合并的代价等于被合并的两果子的重量之和。目标是最小化总的合并代价。 --- #### 解题思路 该问题的核心在于如何通过合理的策略使得总合并代价最小。此问题通常采用 **贪心算法** 来解决,其基本思想如下: 1. 使用优先队列(最小)存储每一果子的重量。 2. 每次从优先队列中取出权重最小的两个果子进行合并,并计算此次合并的代价。 3. 将新合并后的果子重新加入优先队列。 4. 不断重复上述过程,直至队列中仅剩下一果子。 这种做法能够保证每次都选取当前最轻的两果子进行合并,从而尽可能减小后续操作的开销[^2]。 --- #### 算法实现 以下是基于 Python 的具体实现代码: ```python import heapq def merge_fruits(weights): # 初始化最小 heapq.heapify(weights) total_cost = 0 while len(weights) > 1: # 取出当前最轻的两果子 first_min = heapq.heappop(weights) second_min = heapq.heappop(weights) # 计算本次合并的代价 cost = first_min + second_min # 更新总代价 total_cost += cost # 将新的果子放回中 heapq.heappush(weights, cost) return total_cost # 测试数据 weights = [1, 2, 3, 4] result = merge_fruits(weights) print(f"最小化的总合并代价为: {result}") ``` --- #### 复杂度分析 - 时间复杂度:由于使用了优先队列(最小),每次插入或删除操作的时间复杂度为 \(O(\log n)\),而整个过程中需要执行 \(n-1\)合并操作,因此总体时间复杂度为 \(O(n \log n)\)。 - 空间复杂度:主要由优先队列占用的空间决定,空间复杂度为 \(O(n)\)。 --- #### 总结 对于“合并果子”这一类问题,利用贪心算法并通过优先队列优化可以高效求解。需要注意的是,在实际应用中应确保输入数据的有效性和合理性,例如验证是否存在至少两果子可供合并。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值