NEUQOJ-1109

题目

Windbreaker was planning to send his friends some necklaces as New Year gifts. To show sincerity ,he decided to make the necklaces all by himself. He bought some kinds of pearls and each kind of pearls has a different color from others. He wanted to make each necklace consisted of M pearls from different kinds, that’s what he called M-perfect necklace. Windbreaker wanted to know the maximum number of necklaces he could send out to his friends. The number of pearls of each kind and M are given, and now you are asked to tell Windbreaker how many M-perfect necklaces he could make at most .

Input

You will be given a number of cases in the input. Each case starts with a positive integer n(n<=1000),which is the number of different kinds;

The second line contains n positive numbers represent for the number of pearls of each kind which will not exceed 2000.

The third line contains a positive number M(1<=M<=100).

The end of input is indicated by a line containing n=0.

Output

For each test case, output a line containing the Maximum number of M-perfect necklaces.

Sample Input

5

3 3 3 3 3

5

6

1 2 3 4 5 6

5

0

Sample Output

3

3

一开始用方法是将珍珠按照数量从小到大排序,然后从大的开始选起,选完后将大的m种数量都减少1,再进行排序,以此类推。

二分法思路也很清晰,用top表示最多能产生的条数,bottom表示最少能产生的条数,每次试验能否产生mid条项链。检验时,重新计算每一次的sum,如果mid大于pearls[i],则只能用上pearls[i]个,否则加上mid个珍珠。对于能否产生k条项链,只需要sum>=k*m即可,否则配不出k条。

#include<iostream>
#include<algorithm>
using namespace std;

int main(){
    int n,m;
    while(cin>>n&&n!=0){
        int pearls[n];
        int bottom=0,top,mid,sum=0;//用二分法逼近最后能形成的项链数
        for(int i=0;i<n;i++){
            cin>>pearls[i];
            sum+=pearls[i];
        }
        cin>>m;
        top=sum/m;//理论上能产生的最多项链数
        while(bottom<top){
            mid=(bottom+top)/2;//判断能不能产生mid条项链
            sum=0;
            for(int i=0;i<n;i++){//由贪心算法,对于每种珍珠数量和mid之间的较少者min,
                if(pearls[i]>mid)//总有办法使得那min个珍珠被用上在形成的项链中
                    sum+=mid;
                else
                    sum+=pearls[i];
            }
            if(mid*m>sum)
                top=mid-1;
            else
                bottom=mid+1;
        }
        sum=0;
        for(int i=0;i<n;i++){
            if(pearls[i]>bottom)
                sum+=bottom;
            else
                sum+=pearls[i];
        }
        if(bottom*m>sum)//最后一次判断用来检测二分逼近时最后的bottom=mid+1可不可取
            cout<<bottom-1<<endl;
        else
            cout<<bottom<<endl;
    }
    return 0;
}

Ok.

猜你喜欢

转载自blog.csdn.net/qq_29735775/article/details/80617111
今日推荐