zcmu 1882: wjw的括号游戏

1881: wjw的树

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 76   Solved: 29
[ Submit][ Status][ Web Board]

Description

wjw在很早以前种了一棵树,这棵树过了这么多年,已经长到了n米高,wjw为了建造火车站,决定把这棵树给砍倒当作木材,但是这课树太高了,于是wjw准备把这棵树切成m份,每份长度分别为a1,a2,a3...am,显然这种技术活需要一个专业人员——木匠,但是木匠是收费的,他每次切一根长度为x的木材就要收x元,现在wjw想知道最少需要花多少钱就能把这棵树切成他想要的木材。

Input

有多组输入数据,对于每组数据,输入第一行是两个正整数n, m(1≤m≤n≤1000),第二行包含m个正整数,分别是a1,a2,a3...am。输入保证这m个数之和为n。

Output

对于每组数据,输出最少的花费

Sample Input

8 3
2 2 4
6 2
3 3
11 3
5 1 5

Sample Output

Case #1: 12
Case #2: 6
Case #3: 17

HINT

Source


和Huffman树差不多

例如,对于数列{pi}={2,2,4},Huffman树的构造过程如下:   
1.  找到{2,2,4}中最小的两个数,分别是2和2,从{pi}中删除它们并将和4加入,得到{4,4},费用为4。   
2.  找到{4,4}中最小的两个数,分别是4和4,从{pi}中删除它们并将和8加入,得到{8},费用为8。

扫描二维码关注公众号,回复: 2168986 查看本文章

3. 现在,数列中只剩下一个数8,构造过程结束,总费用为4+8=12.

用优先队列写:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
priority_queue<int,vector<int>,greater<int> >a;
int main(){
    int cut=0;
    int n,m,k,x,y;
    while(~scanf("%d %d",&n,&m)){
        cut++;
        while(!a.empty())a.pop();
        for(int i=0;i<m;i++){
            scanf("%d",&x);
            a.push(x);
        }
        int ans=0;
        while(1){
            x=a.top();a.pop();
            y=a.top();a.pop();
            ans=ans+x+y;
            if(a.empty()){break;}
            a.push(x+y);
        }
        printf("Case #%d: %d\n",cut,ans);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qibage/article/details/77486314