CodeCraft-21 and Codeforces Round #711 (Div. 2) B. Box Fitting

B. Box Fitting
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given n rectangles, each of height 1. Each rectangle’s width is a power of 2 (i. e. it can be represented as 2x for some non-negative integer x).

You are also given a two-dimensional box of width W. Note that W may or may not be a power of 2. Moreover, W is at least as large as the width of the largest rectangle.

You have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles.

You cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i. e., any two distinct rectangles must have zero intersection area.

See notes for visual explanation of sample input.

Input

The first line of input contains one integer t (1≤t≤5⋅103) — the number of test cases. Each test case consists of two lines.

For each test case:

the first line contains two integers n (1≤n≤105) and W (1≤W≤109);
the second line contains n integers w1,w2,…,wn (1≤wi≤106), where wi is the width of the i-th rectangle. Each wi is a power of 2;
additionally, maxi=1nwi≤W.
The sum of n over all test cases does not exceed 105.

Output

Output t integers. The i-th integer should be equal to the answer to the i-th test case — the smallest height of the box.

思路:

先将所给的物品从大到小排序,使用优先队列储存每一层所剩的容量,然后每次将最长的物品放入到所剩容量最多的那一层,若不够,则放到新的一层。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
priority_queue<ll>q;
ll a[100010];
bool cmp(ll x,ll y)
{
	return x > y;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n,m;
		scanf("%d%d",&n,&m);
		int ans = 1;
		for(int i = 1; i <= n; i++)
		{
			scanf("%lld",&a[i]);
		}
		sort(a+1,a+1+n,cmp);
		int k = m;
		q.push(k);
		for(int i = 1; i <= n; i++)
		{
			int now = q.top();
			q.pop();
			if(now >= a[i])
			{
				now -= a[i];
				q.push(now);
			}
			else
			{
				q.push(now);
				k = m-a[i];
				q.push(k);
				ans++;
			}
		}
		printf("%d\n",ans);
		while(!q.empty())
		q.pop();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值