N robbers have robbed the bank. As the result of their crime they chanced to get M golden coins. Before the robbery the band has made an agreement that after the robbery i-th gangster would get Xi=Y of all money gained. However, it turned out that M may be not divisible by Y.
The problem which now should be solved by robbers is what to do with the coins. They would like to share them fairly. Let us suppose that i-th robber would get Ki coins. In this case unfairness of this fact is |Xi/Y - Ki/M|. The total unfairness is the sum of all particular unfairnesses. Your task as the leader of the gang is to spread money among robbers in such a way that the total unfairness is minimized.
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Input
The first line of the input file contains numbers N, M and Y (1 <= N <= 1000, 1 <= M, Y <= 10000). N integer numbers follow - Xi (1 <= Xi <= 10000, sum of all Xi is Y).
Output
Output N integer numbers - Ki (sum of all Ki must be M), so that the total unfairness is minimal.
Sample Input
1
3 10 4
1 1 2
Sample Output
2 3 5
题意:有n个人分m个金币,y是要分的总份数,下面一行是分配比率,问你怎么分使每个人的|Xi/Y - Ki/M|最小。
思路:先按照分配比率给每人分,如果是小数,先取整,把其按照与证书的距离排序(因为距离大的算式值小)。再把剩下的金币分下去
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
double ju;
int place;
}a[1005];
int cmp(node x,node y){
if(x.ju==y.ju)
return x.place>y.place;
else
return x.ju>y.ju;
}
int main(){
int t,n;
int sum,i,j;
int ans[1005];
double d,m,y;
double c[1005];
scanf("%d",&t);
while(t--){
scanf("%d%lf%lf",&n,&m,&y);
sum=m;
for(i=1;i<=n;i++){
scanf("%lf",&c[i]);
d=m/y*c[i];
ans[i]=d;
a[i].place=i;
a[i].ju=d-ans[i];
sum-=ans[i];
// printf("i=%d ans=%d ju=%lf\n",i,ans[i],a[i].ju);
}
sort(a+1,a+n+1,cmp);//存的下标是从1开始的
// printf("sun=%d\n",sum);
// for(i=1;i<=n;i++)
// printf("%lf %d\n",a[i].ju,a[i].place);
for(i=1;i<=n && sum;i++){
ans[a[i].place]++;
sum--;
}
for(i=1;i<=n;i++){
if(i!=n)
printf("%d ",ans[i]);
else
printf("%d\n",ans[i]);
}
}
return 0;
}