cf 1066d 思维 二分

题意: 给定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.

 

posted on 2018-10-24 21:33  Helpp  阅读(225)  评论(0编辑  收藏  举报

导航