Educational Codeforces Round 85 B. Middle Class(排序/贪心/水题)
Many years ago Berland was a small country where only nn people lived. Each person had some savings: the ii -th one had aiai burles.
The government considered a person as wealthy if he had at least xx burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:
- the government chooses some subset of people (maybe all of them);
- the government takes all savings from the chosen people and redistributes the savings among the chosen people equally.
For example, consider the savings as list [5,1,2,1][5,1,2,1] : if the government chose the 11 -st and the 33 -rd persons then it, at first, will take all 5+2=75+2=7 burles and after that will return 3.53.5 burles to the chosen people. As a result, the savings will become [3.5,1,3.5,1][3.5,1,3.5,1] .
A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.
The first line contains single integer TT (1≤T≤10001≤T≤1000 ) — the number of test cases.
Next 2T2T lines contain the test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105 , 1≤x≤1091≤x≤109 ) — the number of people and the minimum amount of money to be considered as wealthy.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109 ) — the initial savings of each person.
It's guaranteed that the total sum of nn doesn't exceed 105105 .
Print TT integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.
4 4 3 5 1 2 1 4 10 11 9 11 9 2 5 4 3 3 7 9 4 9
2 4 0 3
可以贪心地考虑,只需要超过x或者大于等于x就是富有的,那么何必多浪费钱呢?如果一个人的钱数超过x,就先++ans,再把超过的钱累加到变量sum里,最后按照钱数从小到大排序,从后往前扫一遍数组,对于不足x的人看看能否用sum使之钱数达到x。(为保证人数尽可能多,先满足钱数与x差距小的人)
注意:It's guaranteed that the total sum of nn doesn't exceed 105105. 所以这个复杂度是没问题的。
#include <bits/stdc++.h> using namespace std; int n,x,a[100005]; int main() { int t; cin>>t; while(t--) { scanf("%d%d",&n,&x); int i; int ans=0; long long sum=0;//sum存储的是超过x的钱数 for(i=1;i<=n;i++) { scanf("%d",&a[i]); if(a[i]>=x)ans++,sum+=a[i]-x; } sort(a+1,a+n+1); for(i=n;i>=1;i--) { if(sum<=0)break; if(a[i]<x) { if(x-a[i]<=sum) { ans++; sum-=(x-a[i]); } } } printf("%d\n",ans); } return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!