1. 程式人生 > 其它 >箱子打包(貪心策略)

箱子打包(貪心策略)

貪心策略練習

1045. 箱子打包

單點時限:2.0 sec

記憶體限制:256 MB

有一組 1 維的物品需要打包進一批同樣的箱子中。所有的箱子有完全一樣的長度 l 以及每一個物品長度 li<=l. 我們要找到一個最小的數字 q, 使得 :

(1) 每個箱子最多包含兩個物品

(2) 每個物品要被包含在 q 個箱子中的一箇中

(3) 在箱子中物品的總長度不能超過 l

你的任務是,給定 n 個整數,l,l1,l2....ln, 計算最小的箱子總數 q.

輸入格式

第一行包含一個數字 n(1<= n <= 10^5), 表示有幾個物品。第二行包含一個整數表示了箱子的長度 l (l<=10000). 接下去的 n 行是表示了每個物品的長度。

輸出格式

輸出一個整數,表示能夠包含所有物品的最小的箱子總數。
提示 :

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.

樣例

input
10
80
70
15
30
35
10
80
20
35
10
30
output
6
解答:
/*
-------------------------------------------------
   Author:       wry
   date:         2022/3/1 17:10
   Description:  test
-------------------------------------------------
*/ #include <bits/stdc++.h> using namespace std; const int MAXN = 1e5+10; int project[MAXN]; //商品長度資訊 int main() { int n,l,number=0; cin >> n >> l; for (int i=0;i<n;i++) { cin >> project[i]; } sort(project,project+n); //從小到大 int i=0,j=n-1;
while(i<=j) { if (i==j) { number++; break; } else { //p<q if (project[i]+project[j]<=l) { number++; i++; j--; } else { number++; j--; } } } cout << number << endl; return 0; }