Educational Codeforces Round 85B(sort+reverse+前缀和)

B. Middle Class

传送门(题目地址)
在这里插入图片描述
在这里插入图片描述

input

4
4 3
5 1 2 1
4 10
11 9 11 9
2 5
4 3
3 7
9 4 9

output

2
4
0
3

题意:

问以群人是否可以共同富裕。—即最多可以多少个人分配后,可以达到x

题解

数据量不大,直接暴力:


  1. 先对每个数排序
  2. 为了操作方便,用一次reverse(a,a+n)(把数组中的元素倒置)
    先接考虑最大值
  3. 开始遍历数组,用一个前缀和sum去维护,当sum >=(i+1)x
    表示当前为i时是可以扶持的。ans=i+1

AC代码

#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+10;
ll a[maxn];
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t;
    cin>>t;
    while(t--)
    {
        ll x,n;
        cin>>n>>x;
        for(int i=0; i<n; i++)cin>>a[i];
        sort(a,a+n);
        reverse(a,a+n);
        ll sum=0, ans=0;
        for(int i=0; i<n; i++)
        {
            sum=sum+a[i];
            if(sum>=x*(i+1))ans=i+1;
        }
        cout<<ans<<endl;
    }
    return 0;
}
发布了8 篇原创文章 · 获赞 8 · 访问量 76

猜你喜欢

转载自blog.csdn.net/qq_45377553/article/details/105459285