A Boring Game

题面:
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.

样例:

1
3
1.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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值