Souvenirs packet (greedy algorithm Center Weighted + sort)
Problem Description
New Year's Day approaching, the school will learn ⽣ Lele souvenir New Year's party in charge of issuing ⼯ for. So the students to the party obtained
Souvenirs value is relatively balanced, he wanted to buy souvenirs into ⾏ grouped according to price, but each group can include up to two souvenirs, and
And the price of each set of souvenirs and can not exceed ⼀ a given integer. In order to ensure that within the shortest possible time finished all the souvenirs, music
Le hopes minimum number of packet destination time.
Your task is to write ⼀ a program to find the minimum number of packets all packets ⽅ case ⼀ species, the minimum number of packets output destination time.
START input format
START input comprising n + 2 ⾏:
The first 1 ⾏ include
⼀ integers W , each of souvenirs and a price limit.
Of 2 ⾏ is ⼀ integers n- , it represents the total number of items available to souvenirs.
Of 3 ~ n + 2 ⾏ each ⾏ Contains either positive integer pi (5 <= pi <= w), corresponding Prices souvenirs.
Output Format
Outputs only ⼀ ⾏, Contains either integer, i.e., the minimum number of packets destination time.
Sample lose START
100
9
90
20
20
30
50
60
70
80
90
Sample Output
6
Scale data and conventions
50% of the full data EMPTY: . 1 <= n-<= 15
100% of the full data EMPTY: . 1 <= n-<= 30000, 80 <= W <= 200 is
Analysis: + greed Center Weighted Sort. ⼩ to start sorting zoomed, i, j pointers are from left to right, right to left traversal.
If a [i] + a [j] <= w, then these two items are placed with START ⼀ group, and moves the pointer at the same time;
Otherwise, only the j points to a separate article release START ⼀ groups, move the pointer j ij ... until all items are traversed ~
Note: Each group only two items, according to the meaning of problems
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int main() {
int w, n;
scanf("%d %d", &w, &n);
int *a = new int[n];
for( int i = 0; i < n; i++)
scanf("%d", &a[i]);
sort(a, a+n);
int i = 0, j = n-1, cnt = 0;
while( i <= j) {
if( a[i] + a[j] <= w) {
i++;
}
cnt++;
j--;
}
cout << cnt;
return 0;
}