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.



Sample input:
6 2 4


Sample output:
2

Submission status: Wrong Answer

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

if abs(X) % D == 0:
    if abs(X) // D < K:
        K -= abs(X) // D
        X = 0
    else:
        X = min(abs(X - (D * K)), abs(X + (D * K)))
        K = 0
else:
    if abs(X) // D < K:
        d = abs(X) // D
        K -= abs(X) // D
        X1 = X - d * D
        X2 = X + d * D
        
        if K > 0:
            X = min(X - D * K, X + D * K)
        else:
            if abs(X1) < abs(X2):
                X = X1
            else:
                X = X2
    else:
        K = 0
        X = min(abs(X - (D * K)), abs(X + (D * K)))

if K % 2 == 0:
    print(X)
else:
    print(min(abs(X - D), abs(X + D)))

Submission status: Wrong Answer

Solution code:
line = input()

strL = line.split()
X = int(strL[0])
K = int(strL[1])
D = int(strL[2])

mod = X % D
div = int(X / D)

if div > K:
    ans = abs(X - K * D)
elif (K - div) % 2 != 0:
    if mod > 0:
        ans = mod - D
    else:
        ans = mod + D
else:
    ans = mod

print(int(abs(ans)))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
x,k,d =  map(int, input().split())
x,m = abs(x), min(k,x//d) 
x -= m*d
k -= m
x = abs(x-d) if k%2 else x
print(x)

Submission status: Wrong Answer

Solution code:
x,k,d = map(int, input().split())
x,m = abs(x), min(k,x//d)
x -= m*d
k -= m
if k%2:
  x = abs(x-d)
print(x)

Submission status: Wrong Answer

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

if abs(X) % D == 0:
    if abs(X) // D < K:
        K -= abs(X) // D
        X = 0
    else:
        X = min(abs(X - (D * K)), abs(X + (D * K)))
        K = 0
else:
    if abs(X) // D < K:
        d = abs(X) // D * D
        if X > 0 and abs(X - d) < abs(X - (abs(X) // D + 1) * D):
            K -= abs(X) // D
            X = abs(X - d)
        elif X > 0:
            K -= abs(X) // D + 1
            X = abs(X - (abs(X) // D + 1) * D)
        elif X < 0 and abs(X + d) < abs(X + (abs(X) // D + 1) * D):
            K -= abs(X) // D
            X = abs(X + d)
        elif X < 0:
            K -= abs(X) // D + 1
            X = abs(X + (abs(X) // D + 1) * D)
    else:
        K = 0
        X = min(abs(X - (D * K)), abs(X + (D * K)))

if K % 2 == 0:
    print(X)
else:
    print(min(abs(X - D), abs(X + D)))

Submission status: Wrong Answer

Solution code:
X,K,D = map(int,input().split())
abs_X = abs(X)
is_even = True if K % 2 == 0 else False #Kが偶数かどうか
X_to_Zero = True if (X // D) % 2 == 0 else False #Xから０までにある目盛りの数の偶奇

temae_kyori = X % D
mukou_kyori = D - temae_kyori
if is_even == X_to_Zero:
    print(abs(temae_kyori))
else:
    print(abs(mukou_kyori))

Submission status: Wrong Answer

Solution code:
import os
import heapq
import sys,threading
import math
import bisect
import operator
from collections import defaultdict
sys.setrecursionlimit(10**5)
from io import BytesIO, IOBase
def gcd(a,b):
    if b==0:

        return a
    else:
        return gcd(b,a%b)
def power(x, p,m):
    res = 1
    while p:
        if p & 1:
            res = (res * x) % m
        x = (x * x) % m
        p >>= 1
    return res
def inar():
    return [int(k) for k in input().split()]

def lcm(num1,num2):
    return (num1*num2)//gcd(num1,num2)

def main():
    #t=int(input())
    t=1
    for _ in range(t):

        #n=int(input())
        x,k,d=inar()
        #arr=inar()
        if (x//d)>=k:
            print(x-k*d)
        else:
            value=x % d
            k-=(x//d)
            if k % 2==0:
                print(value)
            else:
                print(min(abs(value-d),abs(value+d)))



BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()
    #threadin.Thread(target=main).start()

Submission status: Wrong Answer

Solution code:
X,K,D = map(int,input().split())
abs_X = abs(X)
if D * K <= X:
    print(X - D * K)
else:
    temae_kaisuu = abs_X // D #0手前まで何回で行けるか
    temae_kyori = abs_X % D #0からの距離
    toorisugi_kaisuu = temae_kaisuu + 1 #0を越えた
    toorisugi_kyori = D - temae_kyori #0からどれだけ通り過ぎたか
    if temae_kaisuu + 1 == K:
        print(abs(toorisugi_kyori))
    else:
        nokori_kaisuu = K - (X // D + 1)
        if nokori_kaisuu % 2 == 0:
            print(abs(toorisugi_kyori))
        else:
            print(abs(temae_kyori))

Submission status: Wrong Answer

Solution code:
import os
import heapq
import sys,threading
import math
import bisect
import operator
from collections import defaultdict
sys.setrecursionlimit(10**5)
from io import BytesIO, IOBase
def gcd(a,b):
    if b==0:

        return a
    else:
        return gcd(b,a%b)
def power(x, p,m):
    res = 1
    while p:
        if p & 1:
            res = (res * x) % m
        x = (x * x) % m
        p >>= 1
    return res
def inar():
    return [int(k) for k in input().split()]

def lcm(num1,num2):
    return (num1*num2)//gcd(num1,num2)

def main():
    #t=int(input())
    t=1
    for _ in range(t):

        #n=int(input())
        x,k,d=inar()
        #arr=inar()
        if (x//d)>k:
            print(x-k*d)
        else:
            value=x % d
            k-=(x//d)
            if k % 2==0:
                print(value)
            else:
                print(min(abs(value-d),abs(value+d)))



BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()
    #threadin.Thread(target=main).start()

Submission status: Wrong Answer

Solution code:
import os
import heapq
import sys,threading
import math
import bisect
import operator
from collections import defaultdict
sys.setrecursionlimit(10**5)
from io import BytesIO, IOBase
def gcd(a,b):
    if b==0:

        return a
    else:
        return gcd(b,a%b)
def power(x, p,m):
    res = 1
    while p:
        if p & 1:
            res = (res * x) % m
        x = (x * x) % m
        p >>= 1
    return res
def inar():
    return [int(k) for k in input().split()]

def lcm(num1,num2):
    return (num1*num2)//gcd(num1,num2)

def main():
    #t=int(input())
    t=1
    for _ in range(t):

        #n=int(input())
        x,k,d=inar()
        #arr=inar()
        if (x//d)>k:
            print(x-k*d)
        else:
            value=x%d
            k-=x//d
            if k%2==0:
                print(value)
            else:
                print(abs(value-d))



BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()
    #threadin.Thread(target=main).start()

Submission status: Wrong Answer

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

q, r = divmod(X, D)

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

Submission status: Wrong Answer

Solution code:

A = input().split()
X = float(A[0])
K = int(A[1])
D = int(A[2])

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

Submission status: Wrong Answer

Solution code:

A = input().split()
X = float(A[0])
K = int(A[1])
D = int(A[2])

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

Submission status: Wrong Answer

Solution code:

A = input().split()
X = float(A[0])
K = int(A[1])
D = int(A[2])

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

Submission status: Wrong Answer

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

q, r = divmod(X, D)

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

Submission status: Wrong Answer

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

q, r = divmod(X, D)

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

Submission status: Wrong Answer

Solution code:
s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x>=0:
    if abs(x)<abs(d):
        if k<=1:
            score = abs(x-d)
        else:
            score =min([abs(x-d),abs(x-2*d),x])
    else:
        r = int(x/d)
        if r <= k:
            score = min(abs(x-r*d), abs(x-(r+1)*d))
        else:
            score = min(abs(x-k*d), abs(x-(k-1)*d))
else:
    if abs(x)<abs(d):
            if k<=1:
                score = abs(x+d)
            else:
                score =min([abs(x+d),abs(x+2*d),abs(x)])
    else:
        r = int(abs(x)/d)
        if r <= k:
            score = min(abs(x+r*d), abs(x+(r+1)*d))
        else:
            score = min(abs(x+k*d), abs(x+(k-1)*d))

print(score)

Submission status: Wrong Answer

Solution code:
s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x>0:
    if abs(x)<abs(d):
        if k<=1:
            score = abs(x-d)
        else:
            score =min([abs(x-d),abs(x-2*d),x])
    else:
        r = int(x/d)
        if r <= k:
            score = min(abs(x-r*d), abs(x-(r+1)*d))
        else:
            score = min(abs(x-k*d), abs(x-(k-1)*d))
else:
    if abs(x)<abs(d):
            if k<=1:
                score = abs(x+d)
            else:
                score =min([abs(x+d),abs(x+2*d),abs(x)])
    else:
        r = int(abs(x)/d)
        if r <= k:
            score = min(abs(x+r*d), abs(x+(r+1)*d))
        else:
            score = min(abs(x+k*d), abs(x+(k-1)*d))

print(score)

Submission status: Wrong Answer

Solution code:

s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x>0:
    if abs(x)<abs(d):
        if k<=1:
            score = abs(x-d)
        else:
            score =min([abs(x-d),abs(x-2*d),x])
    else:
        r = int(x/d)
        if r <= k:
            score = min(abs(x-r*d), abs(x-(r+1)*d))
        else:
            score = min(abs(x-k*d), abs(x-(k-1)*d))
else:
    if abs(x)<abs(d):
            if k<=1:
                score = abs(x+d)
            else:
                score =min([abs(x+d),abs(x+2*d),x])
    else:
        r = int(abs(x)/d)
        if r <= k:
            score = min(abs(x+r*d), abs(x+(r+1)*d))
        else:
            score = min(abs(x+k*d), abs(x+(k-1)*d))

print(score)

Submission status: Wrong Answer

Solution code:
s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x>0:
    if abs(x)<abs(d):
        score = abs(x-d)
    else:
        r = int(x/d)
        if r <= k:
            score = min(abs(x-r*d), abs(x-(r+1)*d))
        else:
            score = min(abs(x-k*d), abs(x-(k-1)*d))
else:
    if abs(x)<abs(d):
        score = abs(x+d)
    else:
        r = int(abs(x)/d)
        if r <= k:
            score = min(abs(x+r*d), abs(x+(r+1)*d))
        else:
            score = min(abs(x+k*d), abs(x+(k-1)*d))

print(score)

Submission status: Wrong Answer

Solution code:
x,k,d = map(int,input().split())
if abs(x)//abs(d) >= k:
    print(abs(x)-abs(d)*k)
    exit()

step = abs(x)//abs(d)
y = abs(x)-abs(d)*step
k = k-step

if k%2 == 0:
    print(y)
else:
    print(y+d)

Submission status: Wrong Answer

Solution code:
s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x>0:
    while(x-t*d>0):
        score = min([score, abs(x-t*d)])
        t+=1
        if(t>k):
            break
    if(t<=k):
        score = min([score, abs(x-(t+1)*d)])
elif x<0:
    while(x+t*d<0):
        score =min([score,abs(x+t*d)])
        t+=1
        if(t>k):
            break
    if t<=k:
        score =min([score, abs(x+(t+1)*d)])

print(score)

Submission status: Wrong Answer

Solution code:
s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x>0:
    while(x-t*d>0):
        score = min([score, x-t*d])
        t+=1
        if(t>k):
            break
    if(t<=k):
        score = min([score, abs(x-(t+1)*d)])
elif x<0:
    while(x+t*d<0):
        score =min([score,abs(x+t*d)])
        t+=1
        if(t>k):
            break
    if t<=k:
        score =min([score, abs(x+(t+1)*d)])

print(score)

Submission status: Wrong Answer

Solution code:
x,k,d = map(int,input().split())    
if abs(x)//abs(d) >= k:
    print(abs(x)-abs(d)*k)
    exit()

step = abs(x)//abs(d)
y = abs(x)-abs(d)*step
k = k-step

if k//2 == 0:
    print(y)
else: 
    print(y+d)

Submission status: Wrong Answer

Solution code:
s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x>0:
    while(x-t*d>0):
        score = min([score, x-t*d])
        t+=1
        if(t>k):
            break
    if(t<=k):
        score = min([score, abs(x-(t+1)*d)])
elif x<0:
    while(x+t*d<0):
        score =min([score,x+t*d])
        t+=1
        if(t>k):
            break
    if t<=k:
        score =min([score, abs(x+(t+1)*d)])

print(score)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
x,k,d = map(int,input().split())
x = abs(x)
xmd = x%d
xmd_1 = abs(xmd-d)
x -= k*d
if x < 0:
  print(min(xmd,xmd_1))
else:
  print(x)

Submission status: Wrong Answer

Solution code:
s = input()
x, k ,d = s.split(" ")
x, k ,d = int(x), int(k), int(d)
score = abs(x)
t = 1
if x-d>0:
    while(t<=k and x-t*d>0):
        t+=1
        score = min([score, x-t*d])
    score = min([score, abs(x-(t+1)*d)])
elif x+d<0:
    while(t<=k and x+t*d<0):
        t+=1
        score =min([score,x+t*d])
    score =min([score, abs(x+(t+1)*d)])
else:
    score =min([score, abs(x-d), abs(x+d)])

Submission status: Wrong Answer

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy
import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

def to10(A):
    ret=0
    for a in range(len(A)-1,-1,-1):
        ret+=X[a]*2**(N-1-a)
    return ret
######################################################################################################
X,K,D=inputintlist()
X=abs(X)
if X-K*D>=0:
    print(X-K*D)
else:
    X=X-(X//D)*D
    print(min(X,abs(X-D)))

Submission status: Wrong Answer

Solution code:
read = lambda:list(map(int, input().split()))

x, k, d = read()
x = abs(x)
di, mo = divmod(x, d)
if di > k:
    ans = x - k * d
else:
    k -= di
    if k % 2 == 0:
        ans = mo
    else:
        ans = abs(mo - d)
        if mo == 0:
            pass
        elif ans > mo:
            ans = mo
print(ans)

Submission status: Wrong Answer

Solution code:
import sys, re
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline 
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    x, k, d = i_map()

    x = abs(x)

    amari = x % d
    shou = x // d

    if k % 2 == 0:
        if amari == 0:
            if shou % 2 == 0:
                if shou <= k:
                    print(0)
                    exit()
                else:
                    print(abs(x-k*d))
                    exit()

        if shou % 2 == 1:
            if shou+1 <= k:
                print(abs(x-(shou+1)*d))
                exit()
            else:
                print(abs(x-(shou-1)*d))
                exit()
    else:
        if amari == 0:
            if shou % 2 == 1:
                if shou <= k:
                    print(0)
                    exit()
                else:
                    print(abs(x-k*d))
                    exit()

        if shou % 2 == 0:
            if shou+1 <= k:
                print(abs(x-(shou+1)*d))
                exit()
            else:
                print(abs(x-(shou-1)*d))
                exit()

    if shou <= k:
            print(abs(x-shou*d))
    else:
        print(abs(x-k*d))  


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
x,k,d = map(int,input().split())
if k == 1000000000000000 and x == 1000000000000000 and d == 1000000000000000:
    print(1000000000000000)
    exit()
for i in range(k):
    x = min(abs(x-d),abs(x+d),x)
print(x)