NYOJ -804 Gift (二分)

            

Gift

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 2

     描述

HEIHEI was planning to send his friends some necklaces as 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.HEIHEI 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 tell HEIHEI how many M-perfect necklaces he could make at most。

输入
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 fifferent kingds;
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(1<=m<=100).
The end of input is indicated by a line containing n=0.
输出
For each test case , output a line containing the maximum number of M-perfect necklace.
样例输入
5
3 3 3 3 3
5
6
1 2 3 4 5 6
5
0
样例输出
3 
3

题意:给定n种不同颜色的珠子,每种珠子的数目不超过2000,问最多可以组成多少条M完美项链。一条M完美项链是由M颗不同颜色的珠子组成的。

解题思路:如果直接求解最优性是比较困难的。但是,如果考虑本题更弱一点的形式,则会比较简单:给定n种珠子及其数目,问是否能够组成x条M完美链。显然每种珠子最多只能用x次,而只要每种珠子可用的数目的总和大于或等于xXM,一定可以构造出x条M完美链。因此,本题可以结合二分上界和判断可行性来进行求解。二分范围的下界可以设为0,上界则可设为所有珠子数目总和除以M的商。

 
#include <stdio.h>
int main()
{
	int n, i, a[1002], m;
	while(~scanf("%d", &n) && n)
	{
		for(i = 0; i < n; i++)
			scanf("%d", &a[i]);
		scanf("%d", &m);
		if(n<m)
		{
			printf("0\n");
			continue;
		}
		int low = 0, high = 2000000 /*  n*max(a[i])/m   */, mid, ans;
		while(low <= high) 
		{
			mid = (low + high) / 2; //二分项链条数
			int sum = 0;  //记录可用珠子的数目
			for(i = 0; i < n; i++)
			{
				if(a[i] > mid) //珠子用不完
					sum += mid;
				else
					sum += a[i];
			}
			if(sum >= mid * m) //可用珠子数可以组成m条项链
			{
				low = mid + 1;
				ans = mid;  //记录条数
			}
			else
				high = mid - 1;
		}
		printf("%d\n",ans);
	}
	return 0;
}



你可能感兴趣的:(NYOJ -804 Gift (二分))