Codechef Maximum Weight Difference题解

来源:互联网 发布:c语言参考书 编辑:程序博客网 时间:2024/06/06 01:59

Maximum Weight Difference

Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams.

Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry.

However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that the items are split into two groups, and one group contains exactly K items. Then Chef will carry the heavier group, and his son will carry the other group.

Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the maximum possible difference between the weight carried by him and the weight carried by the kid.

Input:

The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each test contains two space-separated integers N and K. The next line contains N space-separated integers W1W2, ..., WN.

Output:

For each test case, output the maximum possible difference between the weights carried by both in grams.

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ K < N ≤ 100
  • 1 ≤ Wi ≤ 100000 (105)

Example:

Input:25 28 4 5 2 108 31 1 1 1 1 1 1 1Output:172


The Only pitfall:

The package with K items could be carried by the son or father, which mean that the K item might be the lighter one or heavier one.


So pack K items which are smallest weight items, 

and pack another K items which are most heavy items.

And compare them which will be better solution.

Choose the better one, and you get the answer.


#ifndef MaximumWeightDifference_H#define MaximumWeightDifference_H#include <stdio.h>#include <stdlib.h>#include <algorithm>using std::sort;class MaximumWeightDifference{public:MaximumWeightDifference(){int T = 0, N = 0, K = 0;scanf("%d", &T);while (T--){scanf("%d %d", &N, &K);int sum = 0, minK = 0, maxK = 0;int *A = (int *) malloc(sizeof(int) * N);for (int i = 0; i < N; i++){scanf("%d", &A[i]);sum += A[i];}sort(A, A+N);for (int i = 0; i < K; i++){minK += A[i];maxK += A[N-i-1];}int minLeft = abs(sum - (minK<<1));int maxLeft = abs(sum - (maxK<<1));printf("%d\n", maxLeft > minLeft? maxLeft : minLeft);free(A);}}};int maximumWeightDifference(){MaximumWeightDifference();return 0;}#endif



1 0
原创粉丝点击