cf 1066d 思维 二分

本文探讨了一种使用二分查找法解决特定装箱问题的算法策略。问题旨在确定在给定数量和大小的箱子中,能按照一定规则装入的最大物品数。通过两种不同的思路,包括正向和逆向装箱模拟,文章详细解释了如何实现这一目标,并提供了完整的C++代码示例。

题意: 给定m个大小为k的箱子 用来装 a[i]大小的物品 

   规则:按照顺序装,等到没有空箱子之后在从前面的箱子中扔出所有,装后面的,

    直到装完  按这个规则 最多装多少物品

 

思路:二分  将题意抽象出来,就是把尽量多的后面的装下去

    也就是处理数组a的后缀就好了  那么起始位置用二分枚举出来。。

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define pb push_back
#define mp make_pair
#define fi first
#define se second

const int  N = 2E5+4;
const ll mod  = 1e9+7;

int a[N];
int n,m,k;
bool check(int ind){
    int num = 1 ;
    int res=k;
    for(int i=ind;i<=n;++i){
        if(a[i]<=res){
            res-=a[i];
        }
        else {
            num++;
            res = k;
            i--;
        }
    }
    return num<=m;
}

int main(){

    cin>>n>>m>>k;

    for(int i=1;i<=n;++i)cin>>a[i];
    int l=1,r=n;
    int ans= -1;

    while(l<=r){
        int mid =(l+r)/2;
      // printf("%d %d\n",l,r);
        if(check(mid)){
            ans = max(ans,n-mid+1);
            ///二分的结果 如果最后不好表示 完全可以在中间求最值啊
            r=mid-1;
        }
        else l=mid+1;
    }

    cout<<ans<<endl;

    return 0;
}

 

思路二:可以倒着装,按照上面的规则模拟一遍 ,最后求出来的结果就是。。

Why it works?

Let's take a look on the last box in the best answer if we will go from left to right in the initial array. Let objects in this box be alst1,alst2,,alstxalst1,alst2,…,alstx. What do we see? xi=1alstik∑i=1xalsti≤k. So all these objects are fit in the last box (obviously). Now if we will iterate over objects from right to left, these objects will fit also! It means that we cannot do worse by such a transform (reversing) at least for the last box.

But what will happen if we can put some of the previous objects in this box? Well, it will not make worse for this box, but what about next boxes (previous boxes in straight notation)? Let objects in the penultimate box be a_{prev_1}, a_{prev_2}, \dots, a_{prev_y}}a_{prev_1}, a_{prev_2}, \dots, a_{prev_y}}. What do we see? These objects are fit in this box (obviously again). What will happen if we will put in the last box one or more objects of this box? Then the left border of objects which we will put in it will not increase because we decrease the number of object in this box. So we can see that for previous boxes this condition is also satisfied.

 

转载于:https://www.cnblogs.com/wjhstudy/p/9846305.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值