A New Year Gift

Problem Description

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
因为可以大致估算出答案的上下界所以可以使用二分法对答案进行逼近
对于给定的数列,对多了一产生sum/m条项链,这个就是答案的上界,下界自然就是0
然后验证某一个解的正确性
如果k大于某一种珍珠i的个数,那么,此种珍珠就选择k个,如果选择多于k个
就会出现i珍珠在一条项链上出现多余一个的情况。如果某种珍珠的个数多于k个那
么就将其全部选入。此时可能出现两种情况,一种是刚刚好可以组成m条项链,
另一种就是可以组成多余m条的项链,那么tem就会大于m*k
 剩下的就是二分的使用了
#include
#include
int n,m,p[1010];
bool check(int k)
{
	int total=0,i;
	for(i=1;i<=n;i++)
	{
		if(k>p[i])
			total+=p[i];
		else total+=k;
	}
	if(total>=k*m) return 1;
	else return 0;
}
int erfen(int low,int high)
{
	int mid;
	mid=(low+high)/2;
	if(low>high) return mid;
	
	if(check(mid))
		erfen(mid+1,high);
	else erfen(low,mid-1);
}
int main()
{
	//freopen("b.txt","r",stdin);
	int i;
	while(scanf("%d",&n)==1&&n)
	{
		int high=0;
		for(i=1;i<=n;i++)
		{
			scanf("%d",&p[i]);
			high+=p[i];
		}
		scanf("%d",&m);
		printf("%d\n",erfen(0,high));
	}
	return 0;
}


你可能感兴趣的:(ACM)