MZL's munhaff function
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 559 Accepted Submission(s): 335
Problem Description
Input
The first line of the input contains a single number T, the number of test cases.
For each test case, the first line contains a positive integer n, and the next line contains n positive integers Ai.
T≤100, 1≤n≤105, ∑n≤106, 1≤Ai≤104.
Output
For each test case, output f(n,1) in a line.
Sample Input
3 3 1 1 1 5 28 26 25 24 1 10 996 901 413 331 259 241 226 209 139 49
Sample Output
5 233 11037
Hint
case 1 : f(1,1)=0 f(1,2)=f(1,1)+3=3 f(1,3)=f(1,2)+3=6 f(2,1)=min(f(2,1)+2,f(1,2))=3 f(2,2)=min(f(2,1)+2,f(1,3))=5 f(2,3)=f(2,2)+2=7 f(3,1)=min(f(3,1)+1,f(2,2))=5
题意:根据题目所给dp方程求f(n,1)。
思路:实际上就是求哈夫曼树。
Ai是Huffman的叶子节点,将A降序排列
dp[i][j]表示放置Ai,还剩j个叶子节点,Huffman的取值。
转移有两种情况:
放在叶子节点处,dp[i+1][j-1],叶子节点还剩j-1个,Ai已经放置好了,考虑Ai+1。
放在非叶子节点处,即下一层,dp[i][j*2],还要考虑次Ai,但是叶子节点扩展两倍了。
和题目给的递推正好互逆。
考虑Bi的值,发现,最后答案f[n][1]就是Huffman树的权值和 减去 叶子节点权值和。
代码:
#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int n,m;
priority_queue<ll,vector<ll>,greater<ll> >Q;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
ll x,ans=0;
scanf("%d",&n);
while(n--)
{
scanf("%lld",&x);
Q.push(x);
}
while(Q.size()>=2)
{
x=Q.top();Q.pop();
x+=Q.top();Q.pop();
ans+=x;
Q.push(x);
}
printf("%lld\n",ans);
Q.pop();
}
return 0;
}