游客 Signup | Login
中文 | En

1500 - 哈夫曼树

哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。

Input

输入有多组数据。

每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。

Output

输出权值。

Examples

Input

2
2 8 
3
5 11 30 

Output

10
62

Solution C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;

typedef struct LNode
{
    ElemType data;
    struct LNode *next;

}LNode ;

typedef struct Link
{
    LNode *head;
}Link;

int Init(Link *L)
{
    L->head=(LNode *)malloc(sizeof(LNode));
    if(!L->head)return ERROR;
    L->head->next=NULL;
    return OK;
}

void insert(Link *L,ElemType e)
{
    LNode *q=L->head;
    LNode *p=(LNode *)malloc(sizeof(LNode));
    if(!q->next)
    {
        p->data=e;
        p->next=q->next;
        q->next=p;
    }
    else
    {
        while(q->next&&q->next->data<e)q=q->next;
        p->data=e;
        p->next=q->next;
        q->next=p;

    }


}
Status Listshanc(Link *L,int i)
{
    LNode *p,*q;
    p=L->head;
    int j=0;
    while(p->next&&j<i-1)
    {
        p=p->next;
        j++;
    }
    if(!p->next||j>=i)return ERROR;
    q=p->next;
    p->next=q->next;
    free(q);
    return OK;
}
void shu(Link L)
{
    LNode *p=L.head->next;
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}

int hfm(Link *L)
{
    int i,a,b,t,s=0;
    LNode *r=L->head;
    while(r->next&&r->next->next)
    {
        a=r->next->data;
        b=r->next->next->data;
        t=a+b;
        s=s+t;
        insert(L,t);
        Listshanc(L,1);
        Listshanc(L,1);

    }
    return s;
}

int main()
{
    int i,n,m,a,b,s=0;
    Link L;

    while(scanf("%d",&n)!=EOF)
    {
        Init(&L);
        for(i=0;i<n;i++)
        {
            scanf("%d",&m);
            insert(&L,m);
        }
        printf("%d\n",hfm(&L));
    }
}


Solution C++

#include <stdio.h>
#include <stdlib.h>

int val[1001];

int cmp(const void * a,const void * b)
{
    return *(int *)a - *(int *)b;
}
int main()
{
    int n;
    int i;
    int ans;
    while(scanf("%d",&n) != EOF)
    {
        ans = 0;
        for(i = 0;i < n;i++) scanf("%d",&val[i]);
        for(i = 1;i < n;i++)
        {
            qsort(&val[i - 1],n - i + 1,sizeof(val[0]),cmp);
            ans += val[i - 1] + val[i];
            val[i] += val[i - 1];
        }
        printf("%d\n",ans);
    }
    return 0;
}
Time Limit 1 second
Memory Limit 32 MB
Discuss Stats
上一题 下一题