原题:
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 .
题意:
给出一些一维长度的棍子放进某最大长度为L 的箱子,每个箱子最多放两根,而且两根之和不能超过L,问至少需要多少个箱子。
题解:
先把棍子按照长度排好顺序,然后取当前最长的棍子和最短的棍子,如果两者之和小于L就把两根都放进去,如果大于L就只把长的那根放进去,直到放完所有的棍子。
代码:AC
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
bool compare(int a,int b)
{
return a>b;
}
int A[100005];
int main()
{
int n;
cin>>n;
int l;
cin>>l;
int i;
for(i=0;i<n;i++)
cin>>A[i];
sort(A,A+n,compare);
int sum=0;
for(i=0;i<n;i++)
{
sum++;
if(A[i]+A[n-1]<=l)
n--;
}
cout<<sum<<endl;
return 0;
}