Santa Claus is planning to bring gifts to n children. He has m cookies and is planning to divide them to n piles. However, as usually problems come unexpected. The child gets unhappy if somebody gets more cookies than him. Each child is characterized by his greediness, the greediness of the i-th child is gi. The unhappines of the i-th child is equal to giai where ai is the number of children that get more cookies than him. Now Santa wants to divide cookies in such a way that the total unhappiness is minimized. Each child must get at least one cookie. Santa would like to give away all m cookies he has. Help him to do so. (1 ≤ n ≤ 30, n ≤ m ≤ 5000)
首先,一定是贪心,更贪婪的孩子,得到的糖果多。
之后,设f[i][j]表示前i个小孩分配j个糖果的最小不高兴值。
则1如果这个小孩分了>1颗糖,所有小孩都减一,不高兴值不变。f[i][j]=f[i][j-i];
2如果这个小孩分了一颗糖,枚举分得一颗糖的人数k.
f[i][j]=f[i-k][j-k]+(i-k)*(s[i]-s[i-k]);
之后方案数,记录前驱,模拟即可。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int n,m,g[35],a[35],s[35],f[35][5005],pre[35][5005],ans[35];
bool b[35][5005];
//f[i][j]前i个小孩分配j个糖果的最小不高兴值
bool cmp(int c,int d)
{
return g[c]>g[d];
}
int main()
{
freopen("cookies.in","r",stdin);
freopen("cookies.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&g[i]);
a[i]=i;
}
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++)
s[i]=s[i-1]+g[a[i]];
memset(f,0x3f,sizeof(f));
f[0][0]=0;
for(int i=1;i<=n;i++)
for(int j=i;j<=m;j++)
{
f[i][j]=f[i][j-i];
for(int k=1;k<=i;k++)//从后向前共有k个小孩获得了1个糖果
if(f[i][j]>f[i-k][j-k]+(i-k)*(s[i]-s[i-k]))
{
f[i][j]=f[i-k][j-k]+(i-k)*(s[i]-s[i-k]);
b[i][j]=1;
pre[i][j]=k;
}
}
printf("%d\n",f[n][m]);
int p=n,t=m;
while(p)
{
if(b[p][t])
{
int x=pre[p][t];
for(int i=p-x+1;i<=p;i++)
ans[a[i]]++;
t-=x;
p-=x;
}
else
{
for(int i=1;i<=p;i++)
ans[a[i]]++;
t-=p;
}
}
for(int i=1;i<=n-1;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n]);
return 0;
}