題面連結:點選跳轉
Description
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 .
Input
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.
Output
Your program has to write the minimal number of bins required to pack all items.
Sample Input
10
80
70
15
30
35
10
80
20
35
10
30
Sample Output
6
Hint
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.
解題思路:
把物品排序一遍,因為要一個箱子固定了最多隻能裝2個物品,那麼如果要使兩個物品的總和盡可能小,那麼需要貪心的每次取最大和最小的合起來,看看能不能裝的下,裝得下就裝減去,否則裝大的進去,每次計數,最後輸出次數即可.
代碼如下:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
int c[(int)1e5+5];
int main(){
ios::sync_with_stdio(false);
int n,len;
while(cin>>n>>len){
for(int i=0;i<n;i++){
cin>>c[i];
}
sort(c,c+n);
int sum=0;
int l=0,r=n-1;
while(l<=r){
if(l==r){//隻有一個物品了直接退出即可,避免出錯
sum++;
break;
}
if(c[l]+c[r]<=len){
sum++;
l++;
r--;
}else{
sum++;
r--;
}
}
cout<<sum<<endl;
}
return 0;
}