题目链接:https://codeforces.com/gym/102770/problem/B
题意
有n个物品,每个物品的容量为a[i],有一种箱子(无数个),每个箱子的容量为c,将物品装入箱中,按照如下装法,请问最少各需要多少个箱子:
- 第一种:每次选择从前往后找到第一个余下空间能够装下当前物品的箱子,把物品装入其中,若没找到,则增加一个箱子,将物品装入增加的箱子中。
- 第二种,每次选择余下空间最小的且能装下当前物品的箱子,若不存在则增加一个箱子,将物品装入增加的箱子中。
思路
- 第一种方式,从前往后找到第一个余下空间大于等于当前物品容量的箱子,可以采用线段树的方式,维护区间最大值,查询过程中先往左子树找,找不到则往右子树找。
- 第二种方式,采用map动态存储每个余下空间的个数,用lower_bound进行查找即可。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
int n,c;
int a[maxn];
struct node
{
int l,r,mx;
}tree[maxn<<2];
void PushUp(int rt)
{
tree[rt].mx=max(tree[rt<<1].mx,tree[rt<<1|1].mx);
}
void Build(int l,int r,int rt)
{
tree[rt].l=l;
tree[rt].r=r;
if(l==r){
tree[rt].mx=c;
return;
}
int mid=(l+r)>>1;
Build(l,mid,rt<<1);
Build(mid+1,r,rt<<1|1);
PushUp(rt);
}
void Update(int rt,int x)
{
if(tree[rt].l==tree[rt].r){
tree[rt].mx-=x;
return;
}
else{
//往左子树更新
if(tree[rt<<1].mx>=x){
Update(rt<<1,x);
PushUp(rt);
return;
}
//往右子树更新
if(tree[rt<<1|1].mx>=x){
Update(rt<<1|1,x);
PushUp(rt);
return;
}
return;
}
}
int Query(int rt,int idx)
{
if(tree[rt].l==tree[rt].r) return tree[rt].mx;
int mid=(tree[rt].l+tree[rt].r)>>1;
if(idx<=mid) return Query(rt<<1,idx);
else return Query(rt<<1|1,idx);
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
scanf("%d %d",&n,&c);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
Build(1,n,1);
int ans1=0,ans2=0;
for(int i=1;i<=n;i++){
Update(1,a[i]);
}
for(int i=1;i<=n;i++){
//若找到了余下空间为c的箱子,说明i-1各箱子已经足够
if(Query(1,i)==c){
ans1=i-1;
break;
}
if(i==n){
ans1=n;
}
}
map<int,int> mp;
for(int i=1;i<=n;i++){
auto p=mp.lower_bound(a[i]);
if(p!=mp.end()){
p->second--;
mp[p->first-a[i]]++;
if(p->second==0) mp.erase(p);//不能忘记erase掉,否则无用的数据会留在map中
}
else{
mp[c-a[i]]++;
ans2++;
}
}
printf("%d %d\n",ans1,ans2);
}
return 0;
}