每日一题洛谷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;
}
相关推荐
00后程序员张1 小时前
从零构建 gRPC 跨语言通信:C++ 服务端与
开发语言·c++
爱凤的小光2 小时前
图漾相机C++语言---Sample_V1(4.X.X版本)完整参考例子(待完善)
开发语言·c++·数码相机
来不及辣哎呀2 小时前
苍穹外卖项目面试总结话术
面试·职场和发展
共享家95272 小时前
LeetCode热题100(1-7)
算法·leetcode·职场和发展
BlackQid3 小时前
深入理解指针Part1——C语言
c++·c
BigDark的笔记4 小时前
[温习C/C++]C++刷题技巧—字符串查找find、find_if、find_first_of和find_last_of
c++
初圣魔门首席弟子5 小时前
c++嵌套类和局部类详细介绍
java·开发语言·c++
橘子师兄5 小时前
类和对象(上)
开发语言·c++
Juan_20125 小时前
P1447题解
c++·数学·算法·题解
祁同伟.5 小时前
【C++】栈、队列、双端队列、优先级队列、仿函数
c++·容器·stl