wtmsb
Time Limit: 1000/100MS (Java/Others) Memory Limit: 131072/131072KB (Java/Others)Submit Status
这天,AutSky_JadeK看到了n张图片,他忍不住说道:“我TM社保!”。
每张图片有一个社保值,他可以合并两张图片,合并所得的图片的社保值是原来两张图片的社保值之和。
每次合并需要消耗的体力也是原来两张图片的社保值之和。 显然,n−1次合并之后,只剩下一张图片。
他想知道,在这个过程中,他消耗的总体力最少是多少。
Input
第一行包含一个整数n,第二行包含n个整数A1,A2,…,An,代表n张图片的社保值。
Output
输出一行,包含一个整数,代表他消耗的总体力最少是多少。Sample input and output
Sample Input Sample Output3
1 2 9
15
Hint
1≤n≤200001≤n≤20000,1≤Ai≤20001≤Ai≤2000
Source
17暑假前集训-数据结构专题 By AutSky_JadeK2017 UESTC Training for Data Structures
My Solution
题意:有n个数,每次可以选择2个数x和y进行合并,其代价和结果都是x+y,要求n-1次合并的最小代价。
优先队列(最小值优先)
把所有的数丢进优先队列,
然后每次如果队列里的元素个数>= 2,
则取出2个数合并记录然后把和丢回队列,
直到元素个数为1.
复杂度 O(nlogn)
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
typedef long long LL;
const int MAXN = 2e4 + 8;
priority_queue<LL, vector<LL>, greater<LL>> pq;
int main()
{
#ifdef LOCAL
freopen("j.txt", "r", stdin);
//freopen("j.out", "w", stdout);
int T = 4;
while(T--){
#endif // LOCAL
//ios::sync_with_stdio(false); cin.tie(0);
int n, a, i, b;
LL ans = 0;
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf("%d", &a);
pq.push(a);
}
int sz = pq.size();
while(sz >= 2){
a = pq.top();
pq.pop();
b = pq.top();
pq.pop();
a = a + b;
ans += a;
pq.push(a);
sz--;
}
cout << ans << endl;
#ifdef LOCAL
cout << endl;
}
#endif // LOCAL
return 0;
}
Thank you!
------from ProLights