分析

一句话:贪心,简单哈夫曼应用,要求的其实是所有结点的值与权值的乘积之和,也就是带权路径长。
可以理解为非叶子节点的权值的和,这里的权值就是零食个数

样例分析: 1 2 3 --- 1 2->3 3 3->6 3+6=9 所以得到6的同学是没有最后相加

因为只需要求最后的结果,不需要建树,可以用优先队列实现,每次挑权值最小的两个相加,将生成的新的结点进入到优先队列中,每次都要将pop的结点的权值加入ans中,直到队列为空
博客 http://www.voidcn.com/article/p-zsktmfnf-nm.html 对于带权路径和讲的比较形象

代码样例

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;
int main()
{
	int n,m;
	while(~scanf("%d",&n))
    {
        priority_queue<int, vector<int> ,greater<int> >Q;//从小到大
        for(int i  = 0;i<n;i++)
        {
            scanf("%d",&m);
            Q.push(m);
        }
        int ans = 0; int t1,t2,temp;
        while(Q.size()>1)
        {
            t1 = Q.top();Q.pop();
            t2 = Q.top();Q.pop();
            temp = t1+t2;
            ans +=temp;
            Q.push(temp);
        }
        printf("%d\n",ans);
    }
}

相关文章:

  • 2021-12-08
  • 2021-06-15
  • 2021-08-07
  • 2021-05-16
  • 2022-01-09
  • 2021-08-05
  • 2021-07-30
  • 2021-10-27
猜你喜欢
  • 2021-05-22
  • 2022-02-27
  • 2021-11-15
  • 2021-08-15
  • 2021-07-30
  • 2021-12-21
  • 2021-07-30
相关资源
相似解决方案