problem
Description
有一棵无穷大的满二叉树,根为star,其余所有点的权值为点到根的距离,如图:
现在你有一些扑克牌,点数从1到13,你要把这些扑克牌全部放到这个树上:
1. 当你把点数为i的扑克牌放在权值为j的点上,那么你会得到i*j的分数。
2. 当你把一个扑克牌放在一个节点上,那么你就不能把别的扑克牌放在这个节点以及这个节点的子树上。
你的目标是最小化你的得分。
Input
文件名为 poker.in
输入第一行为一个数字N,表示你有的扑克牌数;
接下来一行N个数字,数字在1到13之间。
Output
文件名为 poker.out
一个数字,最小得分。
Sample Input
3
5 10 13
Sample Output
43
Data Constraint
Hint
【样例说明】
【数据范围】
30%数据 N<=100
100%数据满足1<=N<=10000.
analysis
正解贪心+小根堆(合并果子)
想要权值最小,一定是把权值小的远离根、权值大的靠近根
哈夫曼树不就是这样的思想建出来的吗?合并果子的话,恰好就是权值小的牌加了更多次数,就是贪心策略了
用堆实现
code
#include<stdio.h>
#define MAXN 10005
using namespace std;
int heap[MAXN];
int n,tot,ans;
int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0' || '9'<ch)if (ch=='-')f=-1,ch=getchar();
while ('0'<=ch && ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
void swap(int &x,int &y){int z=x;x=y,y=z;}
void into(int x)
{
heap[++tot]=x;
for (int i=tot;heap[i]<heap[i/2];i/=2)swap(heap[i],heap[i/2]);
}
int query()
{
int temp=heap[1];heap[1]=heap[tot--];
for (int i=1;i*2<=tot;)
{
int j=(i*2+1>tot || heap[i*2]<heap[i*2+1])?(i*2):(i*2+1);
if (heap[i]<heap[j])break;
swap(heap[i],heap[j]),i=j;
}
return temp;
}
int main()
{
n=read();
for (int i=1;i<=n;i++)into(read());
while (tot>1)
{
int temp=query()+query();
ans+=temp,into(temp);
}
printf("%d\n",ans);
return 0;
}