A Boring Game

来源:互联网 发布:手机电影拍摄软件 编辑:程序博客网 时间:2024/06/05 23:02
题面:
Jeff has got 2n2n real numbers a1,a2,,a2na1, a2, …, a2n. He decides to adjust the numbers. Namely, Jeff consecutively executes nn operations, each of them goes as follows:
choose indexes ii and jj (iji ≠ j) that haven't been chosen yet;
round element aiai to the nearest integer that is no more than aiai.
round element ajaj to the nearest integer that is no less than ajaj.

Jeff wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help him find the minimum absolute value of the difference.

输入:

In the first line is a number TT (T100T≤100) indicating the cases following.
In each case, the first line contains an integer nn (1n20001≤ n ≤ 2000). The next line contains 2n2n real numbers a1,a2,,a2na1,a2,…,a2n (0ai100000 ≤ ai ≤ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
输出:

Print TT lines. In each line print a single real number — the required difference with exactly three digits after the decimal point.

样例:

131.500 1.750 2.000 3.000 4.000 5.000
样例输出:

0.250

题目大意:给定2n个小数,并执行n次操作,每次操作同时操作两个数,把其中的一个向上取整,另一个向下取整。问,在执行完操作以后数列的和与执行操作以前数列的和差值最小是多少。

题解:

这个题实际上也并不难,但比赛时候很多人没做出来。

思路是这样的,因为x.000这样的数不论向上取整还是向下取整都是一样的,所以我们可以不考虑这些数的求和,而仅仅是统计这些数的个数,假设他们的总数为cnt。

而对于其他的小数来说,如果向上取整,那么相当于+1,如果向下取整,相当于不加。

因此我们用所有小数部分的和表示操作以前的数的和,例如sum1 = 0.500+0.750 = 1.250

而用向上取整的小数的个数代表操作后的小数的和,例如sum2 = 1或sum2 = 2或sum2 = 0

这样的话差值就是sum1-sum2了,我们只要求出sum2中可以向上取整的小数个数的范围就行了。

显然,范围是max(0,n-cnt) 到 min(n,2*n-cnt)

AC代码:

#include <iostream>#include <cstdio>using namespace std;const double INF = 1e9;double iabs(double x) {return x>0?x:-x;}int main(){int T;scanf("%d",&T);while(T--){int cnt = 0;double sum = 0;int n;scanf("%d",&n);for(int i = 0;i < 2*n;i++){double d;scanf("%lf",&d);double x = d - int(d);if(x < 0.000001) cnt++;sum += x;}double ans = INF;for(int i  = max(0,n-cnt);i <= min(2*n-cnt,n);i++){ans = min(ans,iabs(sum - (double)i));}printf("%.3lf\n",iabs(ans));}return 0;}




0 0