武汉ACM集训——贪心-3
洛谷 P1090 [NOIP2004 提高组] 合并果子 / [USACO06NOV] Fence Repair G
题解
贪心:
选取两个最小的堆合并,产生新堆。重复合并。
AC代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
const int maxn = 1e4 + 5;
// 优先队列,数值越小,优先级越高
priority_queue<ll, vector<ll>, greater<ll>> a;
int main()
{
ll n;
scanf("%lld", &n);
ll sum = 0;
ll x;
// 存数据
for (int i = 1; i <= n; ++i)
{
scanf("%lld", &x);
a.push(x);
}
for (int i = 1; i <= n - 1; ++i)
{
// 选取两个最小的堆合并
ll y;
x = a.top();
a.pop();
y = a.top();
a.pop();
sum += (x + y);
a.push(x + y);
}
printf("%lld", sum);
return 0;
}