2016级算法期末上机-C.简单·Bamboo's Fight with DDLs III

简单·Bamboo's Fight with DDLs III

分析

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

样例分析: 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);
    }
}
posted @ 2018-01-07 00:16  AlvinZH  阅读(461)  评论(0编辑  收藏  举报