题目: A set of n 1-dimensional items have to be packed in identical bins. All bins have exactly the same length l and each item i has length li<=l . We look for a minimal number of bins q such that ? each bin contains at most 2 items, ? each item is packed in one of the q bins, ? the sum of the lengths of the items packed in a bin does not exceed l . You are requested, given the integer values n , l , l1 , …, ln , to compute the optimal number of bins q .
输入: The first line of the input contains the number of items n (1<=n<=105). The second line contains one integer that corresponds to the bin length l<=10000. We then have n lines containing one integer value that represents the length of the items.
输出: Your program has to write the minimal number of bins required to pack all items.
输入样例: 10 80 70 15 30 35 10 80 20 35 10 30
输出样例: 6
提示: The sample instance and an optimal solution is shown in the figure below. Items are numbered from 1 to 10 according to the input order.
题意: 给你很多大小不一的物品,装到大小为L的盒子里,且每个盒子最多装两个物品,问最少需要多少个盒子
题解: 从小到大排序。 利用两个指针,小指针从小到大,大指针从大到小遍历,使用一个盒子,先取大那头物体装入,大指针左移,如果剩余空间足够再装个小的,则将小的装入,小指针右移,否则继续取盒子,重复到所有物体装完(指针相交错开)。
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
int n,m,ans;
int a[100005];
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
ans=0;
for(int i=0,j=n-1;i<=j;){
ans++;
if(a[i]+a[j]>m){
j--;
}
else{
i++;
j--;
}
}
printf("%d\n",ans);
return 0;
}
|