#include <stdio.h>
#include <stdlib.h>
typedef struct { int n,d,i; } scale_wrk;
int scale_cmp(const void* lv,const void *rv) {
scale_wrk *x=(scale_wrk *)lv, *y=(scale_wrk *)rv;
int u=x->n*y->d, v=y->n*x->d;
return u==v ? (x->i > y->i) : u > v;
}
void scale(int n,int *x,int *w,int D,scale_wrk *t) {
int d,i,s,k;
s=0;for(i=0;i<n;i++) s+=x[i];
d=0;for(i=0;i<n;i++) {
d+=w[i]=x[i]*D/s;
t[i].n=w[i]+1; t[i].d=x[i]; t[i].i=i;
}
if (d>=D) return;
qsort(t
,n
,sizeof(*t
),scale_cmp
); for(k=0;;) {
i=t[k].i; w[i]++; if (++d>=D) break; ++t[k].n;
if (scale_cmp(t+k,t+n-1)) k++;
else {
if (scale_cmp(t+k,t+k+1))
qsort(t
+k
,n
-k
,sizeof(*t
),scale_cmp
); }
}
}
int main(int argc,char **argv) {
enum { n=5 };
scale_wrk t[n];
int i,D,w[n],x[n]={ 30,3,3,31,30 };
for(D=1;D<=200;D++) {
scale(n,x,w,D,t);
for(i
=0;i
<n
;i
++) printf(" %2d",w
[i
]); }
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCnR5cGVkZWYgc3RydWN0IHsgaW50IG4sZCxpOyB9IHNjYWxlX3dyazsKaW50IHNjYWxlX2NtcChjb25zdCB2b2lkKiBsdixjb25zdCB2b2lkICpydikgewogICAgc2NhbGVfd3JrICp4PShzY2FsZV93cmsgKilsdiwgKnk9KHNjYWxlX3dyayAqKXJ2OwogICAgaW50IHU9eC0+bip5LT5kLCB2PXktPm4qeC0+ZDsKICAgIHJldHVybiB1PT12ID8gKHgtPmkgPiB5LT5pKSA6IHUgPiB2Owp9CnZvaWQgc2NhbGUoaW50IG4saW50ICp4LGludCAqdyxpbnQgRCxzY2FsZV93cmsgKnQpIHsKICAgIGludCBkLGkscyxrOwogICAgcz0wO2ZvcihpPTA7aTxuO2krKykgcys9eFtpXTsKICAgIGQ9MDtmb3IoaT0wO2k8bjtpKyspIHsKICAgICAgICBkKz13W2ldPXhbaV0qRC9zOyAKICAgICAgICB0W2ldLm49d1tpXSsxOyB0W2ldLmQ9eFtpXTsgdFtpXS5pPWk7IAogICAgfQogICAgaWYgKGQ+PUQpIHJldHVybjsKICAgIHFzb3J0KHQsbixzaXplb2YoKnQpLHNjYWxlX2NtcCk7CiAgICBmb3Ioaz0wOzspIHsKICAgICAgICBpPXRba10uaTsgd1tpXSsrOyBpZiAoKytkPj1EKSBicmVhazsgKyt0W2tdLm47CiAgICAgICAgaWYgKHNjYWxlX2NtcCh0K2ssdCtuLTEpKSBrKys7CiAgICAgICAgZWxzZSB7IAogICAgICAgICAgICBpZiAoc2NhbGVfY21wKHQrayx0K2srMSkpCiAgICAgICAgICAgICAgICBxc29ydCh0K2ssbi1rLHNpemVvZigqdCksc2NhbGVfY21wKTsgCiAgICAgICAgfQogICAgfQp9CgppbnQgbWFpbihpbnQgYXJnYyxjaGFyICoqYXJndikgewogICAgZW51bSB7IG49NSB9OwogICAgc2NhbGVfd3JrIHRbbl07CiAgICBpbnQgaSxELHdbbl0seFtuXT17IDMwLDMsMywzMSwzMCB9OwogICAgZm9yKEQ9MTtEPD0yMDA7RCsrKSB7CiAgICAgICAgc2NhbGUobix4LHcsRCx0KTsKICAgICAgICBwcmludGYoIiUzZDoiLEQpOwogICAgICAgIGZvcihpPTA7aTxuO2krKykgcHJpbnRmKCIgJTJkIix3W2ldKTsKICAgICAgICBwcmludGYoIlxuIik7CiAgICB9CiAgICByZXR1cm4gMDsKfQ==