Problem:
 Score : 300 points    Problem Statement Takahashi, who lives on the number line, is now at coordinate X . He will make exactly K moves of distance D in the positive or negative direction.  More specifically, in one move, he can go from coordinate x to x + D or x - D .  He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.  Find the minimum possible absolute value of the coordinate of the destination.      Constraints  -10^{15} \leq X \leq 10^{15}  1 \leq K \leq 10^{15}  1 \leq D \leq 10^{15}  All values in input are integers.         Input Input is given from Standard Input in the following format:  X  K  D       Output Print the minimum possible absolute value of the coordinate of the destination.        Sample Input 1 6 2 4      Sample Output 1 2  Takahashi is now at coordinate 6 . It is optimal to make the following moves:   Move from coordinate 6 to ( 6 - 4 = ) 2 .  Move from coordinate 2 to ( 2 - 4 = ) -2 .   Here, the absolute value of the coordinate of the destination is 2 , and we cannot make it smaller.       Sample Input 2 7 4 3      Sample Output 2 1  Takahashi is now at coordinate 7 . It is optimal to make, for example, the following moves:   Move from coordinate 7 to 4 .  Move from coordinate 4 to 7 .  Move from coordinate 7 to 4 .  Move from coordinate 4 to 1 .   Here, the absolute value of the coordinate of the destination is 1 , and we cannot make it smaller.       Sample Input 3 10 1 2      Sample Output 3 8       Sample Input 4 1000000000000000 1000000000000000 1000000000000000      Sample Output 4 1000000000000000  The answer can be enormous.

Solution (Python):

X, K, D = map(int, input().split())

n = abs(X) // D
if n <= K:
    if X >= 0:
        res = X - D * n
        if (K - n) % 2 == 1:
            print(abs(res - D))
        else:
            print(res)
    else:
        res = X + D * n
        if (K - n) % 2 == 1:
            print(abs(res + D))
        else:
            print(abs(res))
else:
    if X >= 0:
        res = X - D * K
    else:
        res = X + D * K
    print(abs(res))

Solution (Python):
X, K, D = map(int, input().split())

if K*D<=abs(X):
    print(abs(X)-K*D)
else:
    Y = abs(X)//D
    Z = K - Y
    if Z%2==0:
        print(abs(X)-D*Y)
    else:
        print(abs(abs(X)-D*Y-D))

Solution (Python):
X, K, D = map(int, input().split())
T = abs(X) // D
if T > K:
    print(abs(abs(X) - K*D))
else:
    if (K - T) % 2 == 0:
        print(abs(abs(X) - T*D))
    else:
        print(abs(abs(X) - (T+1)*D))

Solution (Python):
x,k,d = list(map(int, input().strip().split()))
x=abs(x)
y=x//d
if y>=k:
    print(x-k*d)
else:
    z=k-y
    w=x%d
    if w>=d-w:
        if (z-1)%2==0:
            print(d-w)
        else:
            print(w)
    else:
        if z%2==0:
            print(w)
        else:
            print(d-w)

Solution (Python):



import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect
input = sys.stdin.readline




x, k, d = map(int, input().split())
x = abs(x)

if x > k * d:
    print(x - (k*d))
    sys.exit()

n = x // d
x = x - n * d
k -= n

if k % 2 ==0:
    print(x)
else:
    print(abs(x - d))

Solution (Python):
x,k,d = map(int, input().split())
x = abs(x)
a= x//d
b = x%d
if a>=k:
  print(x-k*d)
  exit(0)
c = abs(b-d)
if (k-a)%2==0:
  print(b)
else:
  print(c)

Solution (Python):
X, K, D = map(int, input().split())
if X > 0 and X - K * D >= 0:
  print(X - K * D)
elif X < 0 and X + K * D <= 0:
  print(abs(X + K * D))
elif K % 2:
  print(min((X+D) % (2*D), abs((X+D) % (2*D)-2*D)))
else:
  print(min(X % (2*D), abs(X % (2*D)-2*D)))

Solution (Python):
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

X, K, D = map(int, read().split())

def main(X, K, D):
    L = X - D * K
    R = X + D * K
    if L >= 0:
        return L
    if R < 0:
        return -R
    t = (-L) // (D + D)
    ans = -L
    for i in range(t - 10, t + 10):
        x = L + (D + D) * i
        if L <= x <= R:
            ans = min(ans, abs(x))
    return ans

print(main(X, K, D))

Solution (Python):
X, K, D = map(int, input().split())
now = 0
if abs(X) - abs(D)*K >= 0:
    now = abs(X) - abs(D)*K
    print(now)
else:
    t = abs(X) // abs(D)
    remain = K - t
    now = abs(X) % abs(D)
    if remain % 2 == 0:
        print(now)
    else:
        print(abs(now - abs(D)))

Solution (Python):
X,K,D = map(int,input().split())
ans = 0
if X<0:
  X = (-1)*X
  
if X-K*D >=0:
  ans = X-K*D
else:
  Y = int(X/D)
  Z = X%D
  if (K-Y)%2==0:
    ans = Z
  if (K-Y)%2==1:
    ans = D-Z
print(ans)

Solution (Python):
import sys
import  math
import fractions
from collections import defaultdict
import copy
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

X,K,D=nm()
X=abs(X)
if(K*D<=X):
    print(X-K*D)
    sys.exit(0)
else:
    tmp=X%D
    tmp2=K-(X//D)
    if(tmp2%2==0):
        print(tmp)
        sys.exit(0)
    else:
        print(D-tmp)
        sys.exit(0)

Solution (Python):
x, k, d = map(int,input().split())
x = abs(x)

if k*d <= x:
    res = x - k*d
else:
    temp = x // d
    temp_x = x - temp*d
    temp_k = k - temp
    
    if temp_k%2 == 0:
        res = temp_x
    else:
        res = abs(temp_x - d)
print(res)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

x,k,d=nii()

dist=abs(x)

num=dist//d

if num>k:
  print(abs(dist-d*k))
  exit()
else:
  k-=num
  dist1=dist-d*num

  if k>=1:
    dist2=abs(dist1-d)
    if dist2<=dist1:
      k-=1
      dist1=dist2

if k%2==0:
  print(dist1)
else:
  print(min(abs(dist1+d),abs(dist1-d)))

Solution (Python):
x, k, d = map(int, input().split())

if -d*k+x < 0:
    t = d*k-x
    p = t//(2*d)
    l = []
    
    for i in range(-1, 2):
        s = p+i
        if 0 <= s <= k:
            
            l.append(abs(2*d*s-d*k+x))
    if len(l) > 0:
        ans = min(l)
    else:
        ans = abs(2*d*k-d*k+x)

else:
    ans = -d*k+x
print(ans)

Solution (Python):

X,K,D = map(int,input().split())
n = abs(X)//D
if K<n:
    print(min(abs(X+K*D),abs(X-K*D)))
else:
    K -= n
    ans = min(abs(X+n*D),abs(X-n*D))
    if K%2==0:
        print(ans)
    else:
        print(D-ans)

Solution (Python):
X,K,D = [int(i) for i in input().split()]
X = abs(X)
M = X//D
if K <= M:
    print(X - K*D)
    exit()
X = X - M*D
K -= M
if K%2 == 0:
    print(X)
else:
    print(abs(X-D))

Solution (Python):
X, K, D = [int(n) for n in input().split()]
if X < 0:
    X = -X

if X - K * D >= 0:
    print(X - K * D)
else:
    R = X % D
    C = (X - R) // D
    if (K - C) % 2 == 0:
        print(R)
    else:
        print(D - R)

Solution (Python):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):   
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    AtoZ = list('abcdefghijklmnopqrsruvwxyz') 
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    class SegTree:
        """
        ref: https://qiita.com/takayg1/items/c811bd07c21923d7ec69
        init(init_val, ide_ele): 配列init_valで初期化 O(N)
        update(k, x): k番目の値をxに更新 O(logN)
        query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
        """
        def __init__(self, init_val, segfunc, ide_ele):
            """
            init_val: 配列の初期値
            segfunc: 区間にしたい操作
            ide_ele: 単位元
            n: 要素数
            num: n以上の最小の2のべき乗
            tree: セグメント木(1-index)
            """
            n = len(init_val)
            self.segfunc = segfunc
            self.ide_ele = ide_ele
            self.num = 1 << (n - 1).bit_length()
            self.tree = [ide_ele] * 2 * self.num
            
            for i in range(n):
                self.tree[self.num + i] = init_val[i]
            
            for i in range(self.num - 1, 0, -1):
                self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

        def update(self, k, x):
            """
            k番目の値をxに更新
            k: index(0-index)
            x: update value
            """
            k += self.num
            self.tree[k] = x
            while k > 1:
                self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
                k >>= 1

        def query(self, l, r):
            """
            [l, r)のsegfuncしたものを得る
            l: index(0-index)
            r: index(0-index)
            """
            res = self.ide_ele
            l += self.num
            r += self.num
            while l < r:
                if l & 1:
                    res = self.segfunc(res, self.tree[l])
                    l += 1
                if r & 1:
                    res = self.segfunc(res, self.tree[r - 1])
                l >>= 1
                r >>= 1
            return res

    
    
    
    
    
    
    
    

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)
            
        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    
    def warshall_floyd(number_vertex, XYD, shift_one_for_vertex=False):
        
        
        
        
        
        d = [[float("inf")]*number_vertex for i in range(number_vertex)]
        for x, y, dist in XYD:
            if shift_one_for_vertex:
                x = x - 1
                y = y - 1
            d[x][y] = dist
            d[y][x] = dist
        for i in range(number_vertex):
            d[i][i] = 0 
        for k in range(number_vertex):
            for i in range(number_vertex):
                for j in range(number_vertex):
                    d[i][j] = min(d[i][j],d[i][k] + d[k][j])
        return d


    """ initialize variables and set inputs
    
        
        
            
            
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    r_float = lambda: float(r())
    R = lambda: list(map(int, r().split()))
    R_str = lambda: r().split()
    R_map = lambda: map(int, r().split())
    R_float = lambda: list(map(float, r().split()))
    R_tuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    X, K, D = R()
    if X < 0:
        X = -X
    
    if X >= K * D:
        print(X-K*D)
    else:
        tmp = X//D
        K -= tmp
        X -= tmp * D
        if K%2 == 0:
            print(X)
        else:
            print(abs(X-D))

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    


    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Solution (Python):
x, k, d = map(int, input().split())

x = abs(x)

if x >= k * d:
    print(x - k * d)
else:
    div, mod = divmod(x, d)
    if (k - div) % 2 == 0:
        print(mod)
    else:
        print(abs(mod - d))

Solution (Python):

x, k, d = map(int, input().split())
x = abs(x)
if (n := k - x // d) < 0:
    print(x - k * d)
else:
    print(abs(d - x % d) if n % 2 else x % d)

Solution (Python):
x,k,d=map(int,input().split())
if x<0:
    x=-x
t=x//d
if k<=t:
    print(int(x-(d*k)))
else:
    if (k-t)%2==1:
        print(int(abs(x-(d*t)-d)))
    else:
        print(int(x-(d*t)))

Solution (Python):
import sys


def _ia(): return map(int, sys.stdin.readline().strip().split())


def main():
    x, k, d = _ia()
    x = abs(x)
    xm = x % d
    n = (x-xm)//d

    if k >= n:
        if n % 2 == k % 2:
            return xm
        else:
            return -xm + d
    else:
        return x - k * d


if __name__ == "__main__":
    print(main())

Solution (Python):
X, K, D = map(int, input().split())
if X < 0:
  X = -X
a = X // D
b = X % D
if a >= K:
  print(X - K * D)
elif (K - a) % 2 == 0:
  print(b)
else:
  print(D-b)

Solution (Python):
X,K,D=map(int,input().split())
m=min(abs(X)%D, abs(abs(X)%D-D))
f=-1 if abs(X)%D-D<0 else 1

if abs(X)-D*K>m:
    print(abs(X)-D*K)
elif (K-(abs(X)-m*f)//D)%2==0:
    print(m)
else:
    print(abs(min(m+D,m-D)))

Solution (Python):
x, k, d = [int(_) for _ in input().split()]

if x <= 0:
    x = -x

if x-k*d >= 0:
    print(x-k*d)
else:
    n = x//d
    x -= n*d
    if (k-n) % 2 == 1:
        x = abs(x-d)
    
    print(x)

Solution (Python):
def abs(x):
    if x < 0:
        return -x
    return x


def main():
    xkd = [int(_x) for _x in input().split()]
    x = xkd[0]
    k = xkd[1]
    d = xkd[2]
    ax = abs(x)
    if ax-k*d > 0:
        print(ax-k*d)
        return

    i = int(ax/d)
    if (k-i) % 2 == 0:
        print(ax-d*i)
        return
    else:
        print(abs(ax-d*i-d))
        return
    


main()

Solution (Python):


import sys
input=sys.stdin.readline

x,k,d=map(int,input().split())

if k%2==0:
    ans=abs(x)
else:
    ans=min(abs(x-d),abs(x+d))
if x>0:
    persuit=x%abs(d)
    moves=x//abs(d)
    if k<=moves:
        ans=min(ans,x-abs(d)*k)
    else:
        if (k-moves)%2==0:
            ans=min(ans,persuit)
        else:
            ans=min(ans,abs(persuit-abs(d)))
else:
    persuit=(-1)*(abs(x)%abs(d))
    moves=abs(x)//abs(d)
    if k<=moves:
        ans=min(ans,abs(x+abs(d)*k))
    else:
        if (k-moves)%2==0:
            ans=min(ans,abs(persuit))
        else:
            ans=min(ans,abs(persuit+abs(d)))
print(ans)

Solution (Python):
import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

X, K, D = rl()

X = abs(X)

c = X // D

if c == K:
	print(X % D)
elif c > K:
	print(X - D*K)
else:
	r = K-c
	if r % 2 == 0:
		print(X % D)
	else:
		print(abs(X % D - D))

Solution (Python):
X, K, D = map(int, input().split())

if X == 0: 
  if K % 2 == 0:
    ans = 0
  else:
    ans = D
else: 
  if X < 0: 
    X *= -1
  C = X - K * D
  if C >= 0:
    ans = C
  else: 
    k = (X - X % D) // D
    if (K - k) % 2 == 0:
      ans = X % D
    else:
      ans = D - X % D
print(ans)

Solution (Python):
X, K, D = map(int, input().split())
X = abs(X)
m_steps = X // D
if m_steps >= K:
    print(X - D * K)
else:
    pos = X - D * m_steps
    K -= m_steps
    if K % 2:
        print(D - pos)
    else:
        print(pos)

Solution (Python):
X,K,D=map(int,input().split())
ans=10**16
X=abs(X)

if X==0:
    if K%2==1:
        ans=abs(D)
    else:
        ans=0
else:
    p=X//D
    if K>=p:
        X-=D*p
        K-=p
        
        if K%2==0:
            ans=X
        else:
            X=min(abs(X+D),abs(X-D))
            ans=X
    else:
        X-=D*K
        ans=X

print(ans)

Solution (Python):
x, k, d = map(int, input().split())
if x < 0:
    a, b = divmod(-x, d)
    if a >= k:
        print(-x - k * d);exit()
    else:
        print(d - b if (k - a) % 2 else b)
elif x:
    a, b = divmod(x, d)
    if a >= k:
        print(x - k * d);exit()
    else:
        print(d - b if (k - a) % 2 else b)
else:
    print(k % 2 * d)

Solution (Python):
X,K,D = map(int,input().split())

X = abs(X)
t = X // D

if K <= t :
    print(X-D*K)
else :
    X -= D*t
    K -= t
    if K%2 == 0 :
        print(X)
    else :
        print(abs(X-D))

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()

def main():
    X, K, D = map(int, input().split())
    if X < 0: X *= -1
    if X >= K * D:
        print(X - K * D)
        return
    q, rem = X // D, X % D
    if q % 2 == K % 2:
        print(rem)
    else:
        print(D - rem)




if __name__ == "__main__":
    main()

Solution (Python):
X,K,D=map(int, input().split())
if abs(X)>=K*D:
  print(abs(X)-K*D)
else:
  a=(abs(X))//D
  A=abs(abs(X)-a*D)
  B=abs(abs(X)-a*D-D)
  if (K-a)%2==0:
    print(A)
  else:
    print(B)

Solution (Python):
x,k,d=map(int,input().split())
if abs(x)//d>k:
    e=d*k
    print(abs(min(x-e,x+e,key=abs)))
else:
    r=abs(x)//d
    t=abs(x)%d
    if (k-r)%2==1:
        print(abs(t-d))
    else:
        print(t)

Solution (Python):
x,k,d = map(int,input().split())
xp = abs(x)
m = xp//d
if m > k:
    print(xp-k*d)
elif (k-m)%2 ==0:
    print(xp-m*d)
else:
    print((m+1)*d-xp)

Solution (Python):
x, k, d = map(int, input().split())
if x < 0:
    x = -x
t = x // d
if k <= t:
    print(x - k*d)
    exit()
x -= t * d
k -= t
if k%2 == 1:
    print(abs(x - d))
else:
    print(x)

Solution (Python):
x, k, d = map(int, input().split())
if k % 2 == 1:
    x = abs(x) - d
    k -= 1
else:
    x = abs(x)
if abs(x) - d * k <= 0:
    temp = x % (d * 2)
    print(min(temp, d * 2 - temp))
else:
    print(abs(x) - d * k)

Solution (Python):
x,k,d=map(int,input().split())
if abs(x)//d>=k:
  print(abs(x)-d*k)
  exit()
c=k-abs(x)//d
ans=abs(x)%d
print([ans,abs(ans-d)][c%2])

Solution (Python):
x,k,d=map(int,input().split())
from math import *
x=abs(x)
if k*d<x:
    ans=x-k*d
elif k*d==x:
    ans=0
else:
    t=ceil(x/d)
    if (k-t)%2==0:
        ans=abs(x-t*d)
    else:
        ans=abs(x-(t-1)*d)
print(ans)

Solution (Python):
X, K, D = map(int, input().split())

X = abs(X)

a = X//D
b = X%D
if a >= K:
  print(b + (a-K)*D)
else:
  if (K - a)%2 == 0:
    print(b)
  else:
    print(D-b)

Solution (Python):
import math

X, K_kai, D = map(int, input().split())

if (abs(X) >= K_kai * D):
    ans = abs(abs(X) - abs(K_kai * D))

else:
    times_low = math.floor(abs(X) / D)
    times_hig = times_low + 1
    
    
    if ((K_kai - times_low) % 2 == 0):
        ans = abs(abs(X) - times_low * abs(D))
            
    else:
        ans = abs(abs(X) - times_hig * abs(D))

print(ans)

Solution (Python):
def main():
    X, K, D = map(int, input().split())
    if abs(X) >= K*D:
        if X <= 0:
            print(abs(X+K*D))
        else:
            print(X-K*D)
    else:
        K -= abs(X) // D
        if K % 2 == 0:
            print(abs(X)%D)
        else:
            print(D-abs(X)%D)

if __name__ == "__main__":
    main()

Solution (Python):
x,k,d = map(int,input().split())
if x>0:      
    a = x//d
    if k < a:
        b = x - k*d
        print(abs(b))
    else:
        if (k-a)%2==0:
            kouho1 = x - a*d
            print(abs(kouho1))
        else:
            kouho2 = x - (a+1)*d
            print(abs(kouho2))
else:
    x = x*(-1)
    a = x//d
    if k < a:
        b = x - k*d
        print(abs(b))
    else:
        if (k-a)%2==0:
            kouho1 = x - a*d
            print(abs(kouho1))
        else:
            kouho2 = x - (a+1)*d
            print(abs(kouho2))

Solution (Python):
X,K,D = map(int,input().split())

X = abs(X)
if X >= K * D:
    print(X - K * D)
else:
    K -= X // D
    X %= D
    if K % 2 == 0:
        print(X)
    else:
        print(D-X)