C - Fence Repair

Description

Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the “kerf”, the extra length lost to sawdust when a sawcut is made; you should ignore it, too.

FJ sadly realizes that he doesn’t own a saw with which to cut the wood, so he mosies over to Farmer Don’s Farm with this long board and politely asks if he may borrow a saw.

Farmer Don, a closet capitalist, doesn’t lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.

Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.

Input

Line 1: One integer N, the number of planks
Lines 2…N+1: Each line contains a single integer describing the length of a needed plank

Output

Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts

Sample

Input

3
8
5
8
Output

34

翻译:农夫约翰想修一小段牧场周围的篱笆。他测量了栅栏,发现他需要N(1≤N≤20000)块木板,每块木板都有一些整数长度的Li(1≤Li≤50000)单位。然后,他买了一块长木板,长度刚好能锯进N块木板(即,木板的长度是长度Li的总和)。FJ忽略了“切口”,即锯切时锯屑所损失的额外长度;你也应该忽略它。

福建悲哀地意识到,他没有一个锯与削减木材,所以他大摇大摆地到农民唐的农场与这个长板,礼貌地问他是否可以借用一把锯。

农民唐,一个秘密资本家,不借给FJ一个锯,而是提出收费农民约翰的每一个N-1削减木板。砍一块木头的费用正好等于它的长度。切割一块长21的木板要花21美分。

农夫唐让农夫约翰决定切割木板的顺序和地点。帮助农场主约翰确定他能花多少钱来制作木板。福建知道,他可以木板以不同的顺序,这将导致不同的费用,因为产生的中间木板是不同的长度。
一个整数N,木板的数量
每行包含一个整数,描述所需木板的长度

第1行:一个整数:他必须花费最少的钱来进行N-1次削减

思路:最少的钱数就是哈夫曼编码长度,要注意这个题目中数据的大小,所以长度需要定义成long long int否则会WA

#include
#include
#include
#include
#include
using namespace std;

int b[20010];
int main()
{
    priority_queue<int, vector<int>,greater<int> >q;
    int n;
    int x1,x2;
    long long int k=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&b[i]);
        q.push(b[i]);
    }
    while(!q.empty())
    {
        x1  =q.top();
        q.pop();
        if(!q.empty())
        {
            x2 = q.top();
            q.pop();
            k += x1+x2;
            q.push(x1+x2);
        }
    }

    printf("%lld\n",k);
    return 0;
}

你可能感兴趣的:(OJ-二叉树)