CareerCup Divide n cakes to k different people

本文探讨如何在派对中将不同口味的蛋糕平均分配给K名成员,确保每位成员获得相同体积的单一口味蛋糕,并尽量减少浪费。通过二分搜索算法实现最优分配策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In a party there are n different-flavored cakes of volume V1, V2, V3 ... Vn each. Need to divide them into K people present in the 
party such that 
- Each member of party gets equal volume of cake (say V, which is the solution we are looking for) 
- A given member should get a cake of single flavour only i.e. You cannot distribute parts of different flavored cakes to same 
member. 
- Minimum volume of cake gets wasted after distribution so that means a maximum distribution policy


-------------------------------------------------------------------------------------


Binary Search: We assume the volumes are int. If not, we should define an epi.


class Solution {
 public:
  bool isDivided(vector<int>& vi, int K, int v) {
     
  }
  int getVol(vector<int>& vi, int K) {
    int sum = 0, l = 0, r = 0, maxVol = 0, mid;
    sort(vi.begin(),vi.end(),greater<int>);
    for (int i = 0; i < vi.size(); ++i)
      sum += vi[i];
    l = vi[0] / K;
    r = sum / K;
    while (l <= r) {
      mid = (l + r) / 2;
      if (isDivided(vi, K, mid)) {
        if (mid > maxVol) {
          maxVol = mid;
          l = mid + 1;
        }
        else 
          r = mid - 1;
      }
      else
        r = mid - 1;
    }
    return maxVol;
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值