Minimize Distance (Codeforces 1585C)
Tags: Greedy, greedy

A total of $$$n$$$ depots are located on a number line. Depot $$$i$$$ lies at the point $$$x_i$$$ for $$$1 \le i \le n$$$.You are a salesman with $$$n$$$ bags of goods, attempting to deliver one bag to each of the $$$n$$$ depots. You and the $$$n$$$ bags are initially at the origin $$$0$$$. You can carry up to $$$k$$$ bags at a time. You must collect the required number of goods from the origin, deliver them to the respective depots, and then return to the origin to collect your next batch of goods.Calculate the minimum distance you need to cover to deliver all the bags of goods to the depots. You do not have to return to the origin after you have delivered all the bags.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,500$$$). Description of the test cases follows.The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$).The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$). It is possible that some depots share the same position.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case, output a single integer denoting the minimum distance you need to cover to deliver all the bags of goods to the depots. 

Note: In the first test case, you can carry only one bag at a time. Thus, the following is a solution sequence that gives a minimum travel distance: $$$0 \to 2 \to 0 \to 4 \to 0 \to 3 \to 0 \to 1 \to 0 \to 5$$$, where each $$$0$$$ means you go the origin and grab one bag, and each positive integer means you deliver the bag to a depot at this coordinate, giving a total distance of $$$25$$$ units. It must be noted that there are other sequences that give the same distance.In the second test case, you can follow the following sequence, among multiple such sequences, to travel minimum distance: $$$0 \to 6 \to 8 \to 7 \to 0 \to 5 \to 4 \to 3 \to 0 \to (-5) \to (-10) \to (-15)$$$, with distance $$$41$$$. It can be shown that $$$41$$$ is the optimal distance for this test case.

Sample Inputs:
4
5 1
1 2 3 4 5
9 3
-5 -10 -15 6 5 8 3 7 4
5 3
2 2 3 3 3
4 2
1000000000 1000000000 1000000000 1000000000

Sample Outputs:
25
41
7
3000000000

Solution (Python):
import sys, io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def min_dist_w_return(x, k):
    total = 0
    i = len(x) - 1
    while i >= 0:
        total += 2 * x[i]
        i -= k
    return total

def minimize_distance(n, k, x):
    xp = []
    xn = []
    for xi in x:
        if xi > 0:
            xp += [xi]
        elif xi < 0:
            xn += [-xi]
    xp.sort()
    xn.sort()
    best = float('inf')
    if len(xp) > 0:
        travel = xp[-1]
        travel += min_dist_w_return(xn, k)
        if len(xp) > k:
            travel += min_dist_w_return(xp[:len(xp) - k], k)
        best = min(best, travel)
    if len(xn) > 0:
        travel = xn[-1]
        travel += min_dist_w_return(xp, k)
        if len(xn) > k:
            travel += min_dist_w_return(xn[:len(xn) - k], k)
        best = min(best, travel)
    if best == float('inf'):
        best = 0
    return best
for _ in range(int(input())):
    (n, k) = map(int, input().split())
    x = list(map(int, input().split()))
    sys.stdout.write(f'{minimize_distance(n, k, x)}\n')

Solution (Python):
from collections import defaultdict
for i in range(int(input())):
    (n, k) = map(int, input().split())
    lst = list(map(int, input().split()))
    lst = sorted(lst)
    lst1 = []
    lst2 = []
    for ele in lst:
        if ele < 0:
            lst1.append(ele)
        elif ele > 0:
            lst2.append(ele)
    n = len(lst1)
    m = len(lst2)
    (var1, var2) = (0, 0)
    if n != 0:
        var1 = lst1[0]
    if m != 0:
        var2 = -lst2[-1]
    s = min(var1, var2)
    for j in range(len(lst2) - 1, -1, -k):
        s += 2 * lst2[j]
    for j in range(0, len(lst1), k):
        s += 2 * abs(lst1[j])
    print(s)

Solution (Python):
for op in range(int(input())):
    I = lambda : list(map(int, input().split(' ')))
    (n, k) = I()
    a = I()
    a2 = [x for x in a if x >= 0]
    a3 = [abs(x) for x in a if x < 0]
    a2.sort()
    a3.sort()
    res = 0
    n1 = len(a2)
    n2 = len(a3)
    if a2:
        res += a2[-1]
        ind = n1 - 1 - k
        while ind >= 0:
            res += 2 * a2[ind]
            ind -= k
    else:
        a2 = [0]
    if a3:
        res += a3[-1]
        ind = n2 - 1 - k
        while ind >= 0:
            res += 2 * a3[ind]
            ind -= k
    else:
        a3 = [0]
    print(res + min(max(a2), max(a3)))