11664. Array partition

 

Given an integer array of 2n integers.

Group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized.

 

Input. The first line contains one number n (n ≤ 105). The second line contains 2n integers, each no more than 105 by absolute value.

 

Output. Print the maximum possible value of the sum

 

Sample input

Sample output

2

4 1 3 2

4

 

 

SOLUTION

greedy

 

Algorithm analysis

Let x1x2 ≤ … x2n be a sorted array. Pair the elements as follows: (x1, x2), (x3, x4), …, (x2n-1, x2n). Then the desired sum is equal to the sum of the elements of the sorted array with odd indices:

min(x1, x2) + min(x3, x4) + … + min(x2n-1, x2n) = x1 + x3 + … + x2n-1

 

Example

The sorted array looks like this: (1, 2, 3, 4).

Let’s pair the numbers: (1, 2), (3, 4). Then the desired sum will be equal to

min(1, 2) + min(3, 4) = 1 + 3 = 4

 

Algorithm realization

Read the input data.

 

scanf("%d", &n);

v.resize(2 * n);

for (i = 0; i < 2 * n; i++)

   scanf("%d", &v[i]);

 

Sort the array.

 

sort(v.begin(), v.end());

 

In the variable s we compute the desired sum.

 

s = 0;

for (i = 0; i < 2 * n; i += 2)

  s += v[i];

 

Print the answer.

 

printf("%lld\n", s);