每日一题洛谷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;
}
相关推荐
lcj251111 分钟前
字符函数,字符串函数,内存函数
c语言·开发语言·c++·windows
吃着火锅x唱着歌16 分钟前
深度探索C++对象模型 学习笔记 第三章 Data语意学(2)
c++·笔记·学习
Chockmans16 分钟前
2026年3月青少年软件编程(Python)等级考试试卷(六级)
开发语言·python·青少年编程·蓝桥杯·pycharm·python3.11·python六级
Imxyk18 分钟前
P9242 [蓝桥杯 2023 省 B] 接龙数列
c++·算法·图论
zjeweler18 分钟前
网安护网面试-1-长亭护网面试
web安全·网络安全·面试·职场和发展
郝学胜-神的一滴22 分钟前
二叉树后序遍历:从递归到非递归的优雅实现
数据结构·c++·程序人生·算法·
亚马逊云开发者22 分钟前
GameLift Servers DDoS防护实战:Player Gateway + Ping Beacons延迟优化 + C++ SDK集成
c++·gateway·ddos
念恒123063 小时前
继承(下) (Inheritance)
c++
H Journey5 小时前
C++之 CMake、CMakeLists.txt、Makefile
开发语言·c++·makefile·cmake
研究点啥好呢9 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件