赞
踩
小明有 n n n 颗石子,按顺序摆成一排,他准备用胶水将这些石子粘在一起。
每颗石子有自己的重量,如果将两颗石子粘在一起,将合并成一颗新的石子,重量是这两颗石子的重量之和。
为了保证石子粘贴牢固,粘贴两颗石子所需要的胶水与两颗石子的重量乘积成正比,本题不考虑物理单位,认为所需要的胶水在数值上等于两颗石子重量的乘积。
每次合并,小明只能合并位置相邻的两颗石子,并将合并出的新石子放在原来的位置。
现在,小明想用最少的胶水将所有石子粘在一起,请帮助小明计算最少需要多少胶水。
输入的第一行包含一个整数 n n n,表示初始时的石子数量。
第二行包含 n n n 个整数 w 1 , w 2 , ⋯ , w n w_1, w_2, \cdots, w_n w1,w2,⋯,wn 依次表示每颗石子的重量。
输出一行包含一个整数,表示最少需要的胶水数。
3
3 4 5
47
8
1 5 2 6 3 7 4 8
546
对于 20 % 20\% 20% 的评测用例, 1 ≤ n ≤ 15 1 \le n \le 15 1≤n≤15。
对于 60 % 60\% 60% 的评测用例, 1 ≤ n ≤ 100 1\leq n \leq 100 1≤n≤100。
对于 80 % 80\% 80% 的评测用例, 1 ≤ n ≤ 1000 1\leq n \leq 1000 1≤n≤1000。
对于所有评测用例, 1 ≤ n ≤ 1 0 5 1\leq n \leq 10^5 1≤n≤105, 1 ≤ w i ≤ 1000 1 \leq w_i \leq 1000 1≤wi≤1000。
蓝桥杯 2020 第一轮省赛 A 组 I 题。
这题一眼贪心,跟之前的合并果子的题其实差不多,就是先优先就考虑质量最小的两个石子合并,但是由于两个石子合并之和,那么就需要知道加入这个石子之和最小的两个石子的质量,可以用一个大根堆来维护,在堆内元素大于1的情况下,每次取堆顶元素,然后相乘,加到答案是,将两个石子 p o p pop pop,再 p u s h push push一下两个石子之和,最后输出答案。
#include <iostream> #include <string> #include <queue> #include <vector> #include <map> #include <set> #include <stack> #include <cmath> #include <algorithm> #define int long long using namespace std; int n,num=0; int a[1050001]; int ok1=0,ok2=0,ok0=0; signed main(){ priority_queue<int,vector<int>,greater<int>> heap; cin>>n; int ans=0; for(int i=1;i<=n;i++){ cin>>a[i]; heap.push(a[i]); } while(heap.size()>1){ int t1=heap.top(); heap.pop(); int t2=heap.top(); heap.pop(); ans+=t1*t2; heap.push(t1+t2); } cout<<ans<<endl; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。