Flowers

题目描述

Recently Jack becomes much more romantic. He would like to prepare several bunches of flowers.

Each bunch of flowers must have exactly M flowers. As Jack does not want to be boring, he hopes that flowers in the same bunch are all different species. Now there are {N}N species of flowers in the flower shop, and the number of the i-th species of flower is a_ia
i

. Now Jack would like to know how many bunches of flowers he can prepare at most.

\textit{(Flowers are used to propose.)}(Flowers are used to propose.)
输入描述:
The first line contains an integer {T}T (1 \le T \le 101≤T≤10) --- the number of test cases.
In the first line of each test case, there are two integers {N}N, {M}M (1 \le N, M \le 300,0001≤N,M≤300000) --- the number of flowers' species and the number of flowers in a bunch.
In the second line of each test case, there are {N}N integers --- the {i}i-th integer indicates ai the number of {i}i-th species' flowers.
输出描述:
For each test case, output one integer in one line --- the answer of the corresponding test case.
示例1
输入
复制

1 
5 3 
1 1 1 2 1

输出
复制

2

题意:

一共有n种花,每种花数量为a[i],要用这些花来做成花束,每个花束必须正好有M多花,且都是不同品种,问最多能做成多少束花

题解:

假设能做成x束花,那么就需要花的总量为xm,一共有n种花,如果a[i]>x,也就是这种花可以用在每一束,也就是第i种花最多用x个,如果a[i]<x,那第i种花就要全部用完才可以。
我们用tot来记录在x个花束的情况下,现有的能提供多少花
也就是看当前x的情况下,每一种花所能做的贡献是多少,tot为贡献和
如果tot>x
m,即供给大于需求,说明情况成立,最佳答案肯定大于等于x
如果tot<xm,即供给小于需求,说明情况不成立,组价答案肯等小于等于x
这样x我们就可以用二分来确定,条件的判断即tot与x
m的关系

代码:

#include<cstdio>
#include<iostream>
#include<queue>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=4e5+8;
typedef long long ll;
ll a[maxn];

int n,m;
bool check(ll x)//x束花 
{
    ll tot=0;
    for(int i=1;i<=n;i++)tot+=min(a[i],x);
    if(tot>=x*m)return 1;
    return 0;
}
int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int t;
    cin>>t;
    while(t--)
    {

        cin>>n>>m;
        ll sum=0;
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            sum+=a[i];
        }
        ll l=0,r=sum/m,ans;
        while(l<=r)
        {
            ll mid=(l+r)>>1;
            if(check(mid))
            {
                l=mid+1;
                ans=mid;
            }
            else r=mid-1;
        }
        cout<<ans<<endl;
    }
    return 0;
}