應邀碼:ae17b8c95ce5aac5
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 species of flowers in the flower shop, and the number of the i-th species of flower is ai. Now Jack would like to know how many bunches of flowers he can prepare at most.
(Flowers are used to propose.)
Input
The first line contains an integer T (1≤T≤10) --- the number of test cases.
In the first line of each test case, there are two integers N, M (1≤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 integers --- the i-th integer indicates ai (1≤ai≤109), the number of i-th species' flowers.
Output
For each test case, output one integer in one line --- the answer of the corresponding test case.
Sample Input
1
5 3
1 1 1 2 1
Sample Output
2
題意:有n種花,每種花有a[i]個,求最多能組成幾個花束(每個花束m朵花,且同一個花束中沒有相同種類的花)
解題思路:這道題可用二分法解決。假設能組成x個花束,則當a[i]大於x時花i最多用x個,當a[i]小於x時,花i可以全部用上 。把這些能用到的花全部都加起來得到sum,問題就在於,這些能用到的花能組成幾束花?我們可以思考,這sum多花很有可能不會剛好組成x束花,會有多餘的,而剛好組成x束花的那部分一定是符合條件的。(如果你認爲會有相同的花在同一束裏,那你是把多餘的花和那x束花混在一塊了)這sum朵花裏,如果滿足sum>=x*m,那x就是有效的。理想情況下x的最大值是num(花的總數)/m,那麼我們只要以sum>=x*m爲判斷條件,從0到num/m進行二分尋找答案就行了。
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=3e5+7;
int n,m;
ll a[maxn];
bool check(ll x)
{
ll sum=0;
for(ll i=1;i<=n;i++) sum+=min(a[i],x);
if(sum>=x*m) return 1;
else return 0;
}
int main()
{
// freopen("input.txt","r",stdin);
int t;
cin>>t;
while(t--)
{
ll num=0;
cin>>n>>m;
for(ll i=1;i<=n;i++)
{
cin>>a[i];
num+=a[i];
}
ll L=0,R=num/m,mid,ans;//從0開始,是因爲x的值是有可能爲0的
while(L<=R)
{
mid=(L+R)/2;
if(check(mid))
{
L=mid+1;
ans=mid;
}
else R=mid-1;
}
cout<<ans<<endl;
}
return 0;
}