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。
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.
解題思路:如果直接求解最優性是比較困難的。但是,如果考慮本題更弱一點的形式,則會比較簡單:給定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;elsesum += a[i];}if(sum >= mid * m) //可用珠子數可以組成m條項鏈{low = mid + 1;ans = mid; //記錄條數}elsehigh = mid - 1;}printf("%d\n",ans);}return 0; }
總結
以上是生活随笔為你收集整理的NYOJ -804 Gift (二分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宁可相信世上有鬼,也不要相信产品经理那张
- 下一篇: 线上一次fullgc搞得鸡飞狗跳后,我总