Minimize Distance (Codeforces 1591C)
Tags: Math, 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):
from bisect import bisect_left, bisect_right

def solve(n, k, depots):
    distance = 0
    depots.sort()
    loc1 = bisect_left(depots, 0)
    loc2 = bisect_right(depots, 0)
    j = n - 1
    while j >= loc2:
        distance += 2 * depots[j]
        j -= k
    j = 0
    while j < loc1:
        distance -= 2 * depots[j]
        j += k
    if loc2 < n and loc1 > 0:
        distance -= max(-depots[0], depots[-1])
    elif loc2 < n:
        distance -= depots[-1]
    elif loc1 > 0:
        distance += depots[0]
    return distance
if __name__ == '__main__':
    ans = []
    for _ in range(int(input())):
        (n, k) = map(int, input().split())
        ans.append(solve(n, k, list(map(int, input().split()))))
    print(*ans, sep='\n')

Solution (Python):
import sys
input = sys.stdin.readline

def positive_dist(x, n, k, last):
    cur = n - 1
    total = 0
    while cur >= 0 and x[cur] > 0:
        total += 2 * x[cur]
        cur -= k
    if last and x[-1] > 0:
        total -= x[-1]
    return total

def negative_dist(x, n, k, last):
    cur = 0
    total = 0
    while cur < n and x[cur] < 0:
        total -= 2 * x[cur]
        cur += k
    if last and x[0] < 0:
        total += x[0]
    return total
t = int(input())
for _ in range(t):
    (n, k) = map(int, input().split())
    x = [int(i) for i in input().split()]
    x.sort()
    if x[0] >= 0:
        print(positive_dist(x, n, k, True))
    elif x[-1] <= 0:
        print(negative_dist(x, n, k, True))
    elif abs(x[0]) > abs(x[-1]):
        print(positive_dist(x, n, k, False) + negative_dist(x, n, k, True))
    else:
        print(positive_dist(x, n, k, True) + negative_dist(x, n, k, False))

Solution (Python):
import bisect
import collections
import itertools
import sys
p2D = lambda x: print(*x, sep='\n')

def II():
    return int(sys.stdin.buffer.readline())

def MI():
    return map(int, sys.stdin.buffer.readline().split())

def LI():
    return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
    return [LI() for _ in range(rows_number)]

def BI():
    return sys.stdin.buffer.readline().rstrip()

def SI():
    return sys.stdin.buffer.readline().rstrip().decode()

def li():
    return [int(i) for i in input().split()]

def lli(rows):
    return [li() for _ in range(rows)]

def si():
    return input()

def ii():
    return int(input())

def ins():
    return input().split()

def drank(d, processing, da, rank):
    tmp = 10 ** 9
    if len(d[da]) == 1:
        return 1
    for di in d[da]:
        if processing[di - 1] == 0:
            processing[di - 1] = 1
            tmp = min(tmp, drank(d, processing, di, rank))
            processing[di - 1] = 0
    rank[da - 1] = tmp + 1
    return tmp + 1

def binary_search(n, a):
    l = len(a)
    low = 0
    high = l - 1
    while high >= low:
        mid = (high + low) // 2
        if a[mid] == n:
            return mid
        elif a[mid] > n:
            high = mid - 1
        else:
            low = mid + 1
    return -1
is_prime = [True] * (10 ** 6 + 1)

def primeseive(n):
    is_prime[0] = is_prime[1] = False
    i = 2
    while i * i <= n:
        if is_prime[i] == True:
            for j in range(i * i, n + 1, i):
                is_prime[j] = False
        i += 1

def solve():
    (n, k) = LI()
    x = LI()
    a = [i for i in x if i > 0]
    b = [i for i in x if i < 0]
    a.sort(reverse=True)
    b.sort()
    alp = []
    la = len(a)
    lb = len(b)
    m = 0
    while m < la:
        alp.append(a[m])
        m += k
    m = 0
    while m < lb:
        alp.append(abs(b[m]))
        m += k
    if la + lb == 0:
        return 0
    else:
        ans = 2 * sum(alp) - max(alp)
        return ans

def main():
    for _ in range(II()):
        sys.stdout.write(str(solve()) + '\n')
if __name__ == '__main__':
    main()