可以看出这是一棵哈夫曼树的若干叶子节点
那么我们开始考虑从一棵空树扩展
如果叶节点数小于n 那么取最小的扩展
否则 如果取最小的扩展 答案更优的话继续 不优的话之后同样不会变优
扩展时记得删去一些最大的数 保持堆的大小
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
using namespace std;
inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}
inline void read(int &x){
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}
const int N=10005;
struct Heap1{
priority_queue<int> Q,del;
void maintain(){ while (!Q.empty() && !del.empty() && Q.top()==del.top()) Q.pop(),del.pop(); }
int top(){ maintain(); return Q.top(); }
void pop(){ maintain(); Q.pop(); }
void push(int x){ maintain(); Q.push(x); }
void erase(int x){ maintain(); del.push(x); }
bool empty(){ maintain(); return Q.empty(); }
int size(){ maintain(); return Q.size()-del.size(); }
}Max;
struct Heap2{
priority_queue<int,vector<int>,greater<int> > Q,del;
void maintain(){ while (!Q.empty() && !del.empty() && Q.top()==del.top()) Q.pop(),del.pop(); }
int top(){ maintain(); return Q.top(); }
void pop(){ maintain(); Q.pop(); }
void push(int x){ maintain(); Q.push(x); }
void erase(int x){ maintain(); del.push(x); }
bool empty(){ maintain(); return Q.empty(); }
int size(){ maintain(); return Q.size()-del.size(); }
}Min;
int n,K;
int a[27];
int Ans=1<<30;
int tot;
int main(){
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
read(n); read(K);
for (int i=1;i<=K;i++) read(a[i]);
for (int i=1;i<=K;i++)
Max.push(a[i]),Min.push(a[i]),tot+=a[i];
while (1){
int x=Min.top(); Min.pop(); Max.erase(x);
tot-=x;
for (int i=1;i<=K;i++)
Min.push(x+a[i]),Max.push(x+a[i]),tot+=x+a[i];
while (Min.size()>n){
int x=Max.top(); Max.pop(); Min.erase(x);
tot-=x;
}
if (Min.size()==n){
if (Ans>tot)
Ans=tot;
else
break;
}
}
printf("%d\n",Ans);
}