每日一题洛谷P8664 [蓝桥杯 2018 省 A] 付账问题c++

P8664 [蓝桥杯 2018 省 A] 付账问题 - 洛谷 (luogu.com.cn)

思路:要使方差小,那么钱不能一下付的太多,可以让钱少的全付玩,剩下还需要的钱再让钱多的付(把钱少的补上)。

将钱排序,遍历一遍,同时将小于平均数的钱加起来计算(平均数是动态,因为后面的钱总比前面的多,总能给前面补钱,这里的误区是直接把平均数设置为总钱数/人数,这样的结果比答案上的方差大),大于等于平均数的钱直接乘上剩下的人数进行计算并跳出循环。

cpp 复制代码
#include<iostream>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
#define int long long
signed main() {
	int n, s;
	cin >> n >> s;
	vector<int> a(n);
	for (int i = 0; i < n; i++)cin >> a[i];
	sort(a.begin(), a.end());
	double x = (double)s / (double)n;
	double c = 0;
	for (int i = 0; i < n; i++) {
		double left = (double)s / (double)(n - i);
		if ((double)a[i] < left) {
			c += (x - (double)a[i]) * (x - (double)a[i]);
			s -= a[i];
		}
		else {
			c += (x - left) * (x - left) * (n - i);
			break;
		}
	}
	c = sqrt(c / n);
	printf("%.4lf", c);
	return 0;
}
相关推荐
端平入洛6 小时前
delete又未完全delete
c++
端平入洛1 天前
auto有时不auto
c++
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
qq_459234422 天前
【题库】| 商用密码应用安全性评估从业人员考核题库(四十)
职场和发展·密码学·学习方法·考核·商用密码·商用密码应用安全性评估·密评
敲敲了个代码2 天前
[特殊字符] 空数组的迷惑行为:为什么 every 为真,some 为假?
前端·javascript·react.js·面试·职场和发展
weiabc2 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼2 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛