| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
优先队列模拟一下,数据答案用long long,52行代码1A数据结构中学过哈夫曼树,构建过程中每次都取值最小的节点和次小的节点构建左右子树,有了父母的几点就不用再考虑了,用优先队列的话,小的优先出对,如果队列中能出队两个元素,就
相加和构成新节点,如果最后优先队列只剩一个节点,则它就是树根,这个节点的值不必再累加到答案上,因为之前进队前已经累加过了。
#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;
const int maxn = 20010;
int a[maxn],n;
struct node
{
long long weight;
friend bool operator<(node n1,node n2)
{
return n1.weight>n2.weight;
}
};
long long solve()
{
priority_queue<node>qu;
node cur,min1,min2; ///min1最小值,min2次小值
for(int i = 0; i < n; i++)
{
cur.weight = a[i];
qu.push(cur);
}
long long ans=0;
while(!qu.empty())
{
min1 = qu.top();
qu.pop();
if(!qu.empty())
{
min2 = qu.top();
qu.pop();
cur.weight = min1.weight + min2.weight;
ans += cur.weight;
qu.push(cur);
}
}
return ans;
}
int main()
{
while(~scanf("%d",&n))
{
for(int i = 0; i < n; i++)
scanf("%d",&a[i]);
printf("%lld\n",solve());
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator