Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

from collections import deque
import sys
def input():
	return sys.stdin.readline()[:-1]

H, W = map(int, input().split())
m = ["#" * (W+2)] + ["#" + input() + "#" for _ in range(H)] + ["#" * (W+2)]
q = deque()
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

step = [[float("inf") for _ in range(W+2)] for _ in range(H+2)]

for h in range(1, H+1):
	for w in range(1, W+1):
		if m[h][w] == "#":
			q.appendleft([h, w])
			step[h][w] = 0

while q:
	label = q.pop()

	for i in range(4):
		h, w = label[0] + dx[i], label[1] + dy[i]
		if m[h][w] != "#" and step[h][w] > step[label[0]][label[1]] + 1:
			q.appendleft([h, w])
			step[h][w] = step[label[0]][label[1]] + 1

ans = 0
for h in range(1, H+1):
	for w in range(1, W+1):
		ans = max(ans, step[h][w])
print(ans)

### FIXED CODE ###

from collections import deque
import sys
def input():
	return sys.stdin.readline()[:-1]

H, W = map(int, input().split())
m = [["#"] * (W+2)] + [["#"] + list(input()) + ["#"] for _ in range(H)] + [["#"] * (W+2)]
q = deque()
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

step = [[float("inf") for _ in range(W+2)] for _ in range(H+2)]

for h in range(1, H+1):
	for w in range(1, W+1):
		if m[h][w] == "#":
			q.appendleft([h, w])
			step[h][w] = 0

while q:
	label = q.pop()

	for i in range(4):
		h, w = label[0] + dx[i], label[1] + dy[i]
		if m[h][w] != "#" and step[h][w] > step[label[0]][label[1]] + 1:
			q.appendleft([h, w])
			step[h][w] = step[label[0]][label[1]] + 1

ans = 0
for h in range(1, H+1):
	for w in range(1, W+1):
		ans = max(ans, step[h][w])
print(ans)
### BUGGY CODE ###

N, K = list(map(int, input().split()))
tree = [int(input()) for i in range(N)]

tree.sort()
m = float("inf")
for i in range(N-K+1):
    d = tree[i : i + K]
    dif = max(d) - min(d)
    m = dif if m > dif else m

print(int(m))

### FIXED CODE ###

N, K = list(map(int, input().split()))
t = [int(input()) for i in range(N)]

t.sort()
m = 10 ** 9
for i in range(N-K+1):
    m = min(t[i+K-1] - t[i], m)

print(int(m))
### BUGGY CODE ###

n = int(input())

tasks = []
for i in range(n):
  a,b = list(map(int,input().split(" ")))
  tasks.append((a,b))

tasks = sorted(tasks, key = lambda x:(x[1],x[0]))

flag = True
now_time = 0
while tasks != []:
  a,b = tasks.pop(0)
  if now_time + a > b:
    flag = False
    break
  else:
    now_time = now_time + a
if flag:
  print("Yes")
else:
  print("No")

### FIXED CODE ###

n = int(input())

tasks = []
for _ in range(n):
  a,b = list(map(int,input().split(" ")))
  tasks.append((a,b))

tasks = sorted(tasks,key = lambda x:x[1])

now_time = 0
flag = True
for a,b in tasks:
  if now_time + a > b:
    flag = False
    break
  now_time += a
if flag:
  print("Yes")
else:
  print("No")
### BUGGY CODE ###

s = input()
l = len(s)
ans = 0
flag = 0
for i in range(3, l):
    for j in range(3, l):
        while (i - j >= 0 and i >= 3) and flag == 0:
            num = int(s[i-j:i+1])
            if num % 2019 == 0:
                ans += 1
                i -= j+1
            else:
                flag = 1
        flag = 0    
print(ans)

### FIXED CODE ###

s = input()
s = s[::-1]
l = len(s)
count = [0] * 2019
res = 0
count[res] = 1
d = 1
for i in s:
    res += int(i) * d
    res %= 2019
    count[res] += 1
    d *= 10
    d %= 2019
print(int(sum([m*(m-1)/2 for m in count])))
### BUGGY CODE ###

import sys

N = int(input())
TASKS = []
for i in range(1, N+1):
    A,B = map(int, input().split())
    TASKS.append([A,B])

TASKS.sort(key=lambda x: x[1])

#print(TASKS)

time = 0

for i in range(1, N+1):
    task = TASKS.pop(0)
    a = task[0]
    b = task[1]
    time += a
    if time <= b:
        continue
    else:
        print("No")
        sys.exit()

print("Yes")


### FIXED CODE ###

import sys

N = int(input())
TASKS = []
time = 0
for i in range(1, N+1):
    A,B = map(int, input().split())
    TASKS.append([A,B])

TASKS.sort(key=lambda x: x[1])

#print(TASKS)

time = 0

for i in range(N):
    task = TASKS[i]
    a = task[0]
    b = task[1]
    time += a
    if time <= b:
        continue
    else:
        print("No")
        sys.exit()

print("Yes")
### BUGGY CODE ###

from heapq import heappop,heappush
def dijkstra(s,n,edge):
  """
  始点sから各頂点への最短距離を返す

  Parameters
  ----------
  s : int
      視点とする頂点（0-indexed）
  n : int
      グラフの要素数
  eage:list
      グラグ

  Returns
  -------
  dist ：list
  始点sから各頂点への最短距離
  """
  dist=[float("inf")]*n
  dist[s]=0
  used=[-1]*n
  hq=[[dist[s],s]]
  while hq:
    d,cur=heappop(hq)
    if dist[cur]<d:continue # 距離が最小でない場合は飛ばす
    for nx,nxd in edge[cur]:
      if dist[cur]+nxd<dist[nx]:
        dist[nx]=dist[cur]+nxd
        used[nx]=cur
        heappush(hq,[dist[cur]+nxd,nx])
  return dist

n,m,s,t=map(int,input().split())
Gs=[[] for i in range(n)]
Gt=[[] for i in range(n)]
for i in range(m):
  u,v,a,b=map(int,input().split())
  Gs[u-1].append([v-1,a])
  Gs[v-1].append([u-1,a])
  Gt[u-1].append([v-1,b])
  Gt[v-1].append([u-1,b])
s-=1
t-=1
yen=dijkstra(s,n,Gs)
snk=dijkstra(t,n,Gt)
cost=[10**15-(yen[i]+snk[i]) for i in range(n)]
for i in range(n-2,-1,-1):
  cost[i]=max(cost[i],cost[i+1])
for c in cost:
  print(c)



### FIXED CODE ###

import sys
input=sys.stdin.readline
from heapq import heappop,heappush
def dijkstra(s,n,edge):
  """
  始点sから各頂点への最短距離を返す

  Parameters
  ----------
  s : int
      視点とする頂点（0-indexed）
  n : int
      グラフの要素数
  eage:list
      グラグ

  Returns
  -------
  dist ：list
  始点sから各頂点への最短距離
  """
  dist=[float("inf")]*n
  dist[s]=0
  used=[-1]*n
  hq=[[dist[s],s]]
  while hq:
    d,cur=heappop(hq)
    if dist[cur]<d:continue # 距離が最小でない場合は飛ばす
    for nx,nxd in edge[cur]:
      if dist[cur]+nxd<dist[nx]:
        dist[nx]=dist[cur]+nxd
        used[nx]=cur
        heappush(hq,[dist[cur]+nxd,nx])
  return dist

n,m,s,t=map(int,input().split())
Gs=[[] for i in range(n)]
Gt=[[] for i in range(n)]
for i in range(m):
  u,v,a,b=map(int,input().split())
  Gs[u-1].append([v-1,a])
  Gs[v-1].append([u-1,a])
  Gt[u-1].append([v-1,b])
  Gt[v-1].append([u-1,b])
s-=1
t-=1
yen=dijkstra(s,n,Gs)
snk=dijkstra(t,n,Gt)
cost=[10**15-(yen[i]+snk[i]) for i in range(n)]
for i in range(n-2,-1,-1):
  cost[i]=max(cost[i],cost[i+1])
for c in cost:
  print(c)
### BUGGY CODE ###

n = input()
a = input().split()
n = int(n)
a = [int(s) for s in a]
s =0

#print(n,a)

for f in range(n):
  
  for g in range(n):

    if g != f:
    	if a[f] == a[g]:
      		#print(a[f], a[g])
      		s = s+1
      
if s>0: print("NO")
else: print('YES')

### FIXED CODE ###

n = input()
a = input().split()
n = int(n)
a = [int(s) for s in a]
a.sort()
#print(a)
s=0

for i in range(len(a)-1):
    #print(a[i],a[i+1])
    
    if a[i]==a[i+1]:
        print("NO")
        s=s+1
        break
        
if s == 0: print("YES")
### BUGGY CODE ###

import sys

def read():
    return sys.stdin.readline().rstrip()

def main():
    n, m, k = map(int, read().split())
    friend = [set() for _ in range(n)]
    block = [set() for _ in range(n)]
    potential = [set() for _ in range(n)]
    for _ in range(m):
        a, b = [int(i) - 1 for i in read().split()]
        friend[a].add(b)
        friend[b].add(a)
    for _ in range(k):
        c, d = [int(i) - 1 for i in read().split()]
        block[c].add(d)
        block[d].add(c)
    sd = set()
    for u in range(n):
        sn = [u]
        pf = set()
        while sn:
            p = sn.pop()
            if p in sd:
                continue
            sd.add(p)
            pf.add(p)
            for f in friend[p]:
                sn.append(f)
        for pfi in pf:
            potential[pfi] |= pf
    print(*[len(potential[i] - friend[i] - block[i] - {i}) for i in range(n)])

if __name__ == '__main__':
    main()

### FIXED CODE ###

import sys
from collections import deque

def read():
    return sys.stdin.readline().rstrip()

def main():
    n, m, k = map(int, read().split())
    friend = [[] for _ in range(n)]
    block = [set() for _ in range(n)]
    potential = [set() for _ in range(n)]
    for _ in range(m):
        a, b = [int(i) - 1 for i in read().split()]
        friend[a].append(b)
        friend[b].append(a)
    for _ in range(k):
        c, d = [int(i) - 1 for i in read().split()]
        block[c].add(d)
        block[d].add(c)
    sd = set()
    for u in range(n):
        if u in sd:
            continue
        sn = deque([u])
        pf = set()
        while sn:
            p = sn.pop()
            if p in sd:
                continue
            sd.add(p)
            pf.add(p)
            for f in friend[p]:
                sn.append(f)
        for pfi in pf:
            potential[pfi] = pf
    print(*[len(potential[i]) - len(block[i] & potential[i]) - len(friend[i]) - 1 for i in range(n)])

if __name__ == '__main__':
    main()
### BUGGY CODE ###

def sol():
    N, Ma, Mb = map(int, input().split())
    items = []
    for _ in range(N):
        a, b, c = map(int, input().split())
        items.append((a, b, c))

    dp = [[[[]] for _ in range(Ma)] for _ in range(N + 1)]

    for i, (a, _, _) in enumerate(items):
        for mod in range(Ma):
            for prev in dp[i][mod]:
                dp[i + 1][mod].append(prev)
            for prev in dp[i][(mod - a) % Ma]:
                dp[i + 1][mod].append(prev + [i])

    maList = filter(lambda A : len(A) > 0, dp[N][0])

    ans = float('inf')
    for addList in maList:
        sumA = 0
        sumB = 0
        cost = 0
        for i in addList:
            sumA += items[i][0]
            sumB += items[i][1]
            cost += items[i][2]
        if sumA * Mb == sumB * Ma:
            ans = min(ans, cost)

    if ans == float('inf'):
        print(-1)
    else:
        print(ans)

sol()

### FIXED CODE ###

def sol():
    N, Ma, Mb = map(int, input().split())

    A = []
    B = []
    cost = []
    sumA = 0
    sumB = 0

    for _ in range(N):
        a, b, c = map(int, input().split())
        A.append(a)
        B.append(b)
        cost.append(c)
        sumA += a
        sumB += b

    dp = [[[float('inf') for _ in range(sumB * 2 + 1)] for _ in range(sumA * 2 + 1)] for _ in range(N + 1)]
    dp[0][0][0] = 0

    for index in range(N):
        for sA in range(sumA + 1):
            for sB in range(sumB + 1):
                dp[index + 1][sA][sB] = min(
                    dp[index + 1][sA][sB],
                    dp[index][sA][sB]
                )
                dp[index + 1][sA + A[index]][sB + B[index]] = min(
                    dp[index + 1][sA + A[index]][sB + B[index]],
                    dp[index][sA][sB] + cost[index]
                )

    ans = float('inf')
    for sA in range(1, sumA):
        for sB in range(1, sumB):
            if sA * Mb == sB * Ma:
                ans = min(ans, dp[N][sA][sB])

    if ans == float('inf'):
        print('-1')
    else:
        print(ans)

sol()
### BUGGY CODE ###

N = int(input())
S =  input()
dp = [0] * N
min_selct = N//2
max_length = 0
for i in range(N):
    max_j = (N -i)//2
    for j in range(max_j):
        current_length = max_j-j
        if S[i:i+current_length] in S[i+current_length:N]:
            max_length = max(max_length,current_length)
            break
print(max_length)

### FIXED CODE ###

n = int(input())
S = input()
N = [0]*n
j = 0
 
for i in range(n):
  while S[i:j] in S[j:n]:
    N[i] = j-i
    j += 1
    
print(max(N))
### BUGGY CODE ###

from operator import itemgetter

import numpy as np

n = int(input())
aaa = list(enumerate(map(int, input().split())))
n2 = 1 << n
arr = np.arange(n2, dtype=np.uint)
bit = np.zeros(n, dtype=np.uint)
mat = np.zeros((n, n2))
for i in range(n):
    b = 1 << i
    bit[i] = b
    mat[i] = (arr & b) > 0
count = np.zeros(n2, dtype=np.uint8)
ans = np.zeros(n2, dtype=np.uint)
aaa.sort(reverse=True, key=itemgetter(1))
for i, a in aaa:
    idx = mat[(bit & i).astype(bool)].all(axis=0) & (count < 2)
    ans[idx] += a
    count[idx] += 1
ans = np.maximum.accumulate(ans[1:])
print(*ans)


### FIXED CODE ###

n = int(input())
aaa = list(map(int, input().split()))
n2 = 1 << n
dp = [[a, 0] for a in aaa]

for j in range(n):
    b = 1 << j
    for i in range(n2):
        if not i & b:
            dpi, dpk = dp[i], dp[i | b]
            if dpk[0] < dpi[0]:
                dpk[1] = max(dpk[0], dpi[1])
                dpk[0] = dpi[0]
            elif dpk[1] < dpi[0]:
                dpk[1] = dpi[0]

ans = []
tmp = 0
for a in dp[1:]:
    tmp = max(tmp, a[0] + a[1])
    ans.append(tmp)
print(*ans)
### BUGGY CODE ###

import math
import collections


k = int(input())
a = list(map(int, input().split()))
c = collections.Counter(a)
s = 0
for i in c.values():
  if i == 1:
    continue
  s += math.factorial(i) // (math.factorial(i - 2) * math.factorial(2))

for i in a:
  j = c[i] - 1
  if j <= 1:
    if j == 0:
      print(s)
      continue
    print(s - 1)
    continue
  b = math.factorial(j) // (math.factorial(j - 2) * math.factorial(2))
  y = math.factorial(j + 1) // (math.factorial(j + 1 - 2) * math.factorial(2))
  d = y - b
  print(s - d)

### FIXED CODE ###

import collections


k = int(input())
a = list(map(int, input().split()))
c = collections.Counter(a)
s = 0
for i in c.values():
  s += i * (i - 1) / 2

for i in a:
  j = c[i] - 1
  b = j * (j - 1) // 2
  y = (j + 1) * j // 2
  d = y - b
  print(int(s - d))
### BUGGY CODE ###

N = int(input())
S = list(input())
Q = []
for i in range(0,N) :
    A = S[0:i]
    B = S[i+1:N]
    for j in range(len(A)) :
        if A[j] == "W" :
            A[j] = 1
        else :
            A[j] = 0
    for k in range(len(B)) :
        if B[k] == "W" :
            B[k] = 0
        else :
            B[k] = 1
    Q.append(sum(A)+sum(B))
print(min(Q))



### FIXED CODE ###

N = int(input())
S = list(input())
ANS = []
ans = 0
for i in range(0,N) :
    if i == 0 :
        ans += S[1:].count("E")
        ANS.append(ans)
    elif S[i-1] == "E" and S[i] == "E" :
        ans -= 1
        ANS.append(ans)
    elif S[i-1] == "W" and S[i] == "W" :
        ans += 1
        ANS.append(ans)
print(min(ANS))
### BUGGY CODE ###

import functools, fractions

n = int(input())
a = list(map(int, input().split()))

gcd_max = 0

for i in range(n):
  ad = a[:]
  if i == 0:
    ad[0] = ad[1]
  else:
    ad[i] = ad[i - 1]
  gcd = functools.reduce(fractions.gcd, ad)
  if gcd > gcd_max:
    gcd_max = gcd

print(gcd_max)

### FIXED CODE ###

from fractions import gcd

n = int(input())
a = list(map(int, input().split()))

gcdl = [0] * n
gcdr = gcdl[:]

gcdl[0]  = a[0]
gcdr[-1] = a[-1] 

for i in range(1, n):
  gcdl[i] = gcd(a[i], gcdl[i - 1])

for i in range(n - 2, -1, -1):
  gcdr[i] = gcd(a[i], gcdr[i + 1])

max_gcd = max(gcdl[-2], gcdr[1])

for i in range(1, n - 1):
  temp_gcd = gcd(gcdl[i - 1], gcdr[i + 1])
  if temp_gcd > max_gcd:
    max_gcd = temp_gcd

print(max_gcd)
### BUGGY CODE ###

n = int(input())
s = input()

c = 0
for i in range(n):
	for j in range(i+1, n):
		for k in range(j+1, n):
			if s[i] != s[j] and s[i] != s[k] and s[j] != s[k] and j-i != k-j:
				c += 1
				# print(s[i], s[j], s[k])
print(c)


### FIXED CODE ###

n=int(input())
s=str(input())
t=len(s)
r=set()
g=set()
b=set()
a=0
for i in range(n):
    if s[i]=='R':
        r.add(i)
    if s[i]=='G':
        g.add(i)
    if s[i]=='B':
        b.add(i)
d=len(r)*len(g)*len(b)
for ri in r:
    for gi in g:
        dist = abs(ri-gi)
        if ri > gi:
            bi = dist + ri
            if bi in b:
                d -= 1
            bi = gi - dist
            if bi in b:
                d -= 1
        else:
            bi = dist + gi
            if bi in b:
                d -= 1
            bi = ri - dist
            if bi in b:
                d -= 1

        if (ri + gi) % 2 == 0:
            bi = (ri+gi)/2
            if bi in b:
                d -= 1
print(d)
### BUGGY CODE ###

X = input()

for i in range (0, 100001):
	X = X.replace("ST", '')
	if X == X.replace("ST", ''):
		print(len(X))
		exit() 

print(len(X))


### FIXED CODE ###

X = str(input())

Tn = 0
Sn = 0
Nagasa = len(X)

for i in range (0, Nagasa):
	if X[i] == 'T':
		if Sn == 0:
			Tn+=1
		else:
			Sn-=1
	else:
		Sn+=1

print(2*Tn)
### BUGGY CODE ###

import math
N,K=map(int,input().split())
A=list(map(int,input().split()))
count=0
before=0
now=1


for i in A:
    now*=i
    count+=1
    if count>K:
        now=now/A[count-K-1]
        if now>before:
            print("Yes")
        else:
            print("No")
    if count>=K:
        before=now


### FIXED CODE ###

import math
N,K=map(int,input().split())
A=list(map(int,input().split()))
count=0
before=0
now=1


for i in range(K,N):
    if A[i]>A[i-K]:
        print("Yes")
    else:
        print("No")
### BUGGY CODE ###

import sys
input = sys.stdin.readline

N, M = map(int, input().split())

sl = []
ans = 0
pen = 0
WA = [0 for _ in range(N)]
for i in range(M):
    p, S = input().split()
    if p in sl:
        continue

    if S == 'AC':
        ans += 1
        sl.append(p)
        pen += WA[int(p) - 1]
    else:
        WA[int(p) - 1] += 1

print(ans, pen)


### FIXED CODE ###

import sys
input = sys.stdin.readline

N, M = map(int, input().split())

sl = set()
ans = 0
pen = 0
WA = [0 for _ in range(N)]
for i in range(M):
    p, S = input().split()
    if p in sl:
        continue

    if S == 'AC':
        ans += 1
        sl.add(p)
        pen += WA[int(p) - 1]
    else:
        WA[int(p) - 1] += 1

print(ans, pen)
### BUGGY CODE ###

N = int(input())
A = [int(input()) for _ in range(N)]
current = 0
ans = 0

while True:
    current = A[current] - 1
    ans += 1
    if current == 0:
        print(-1)
        break

    if current == 1:
        print(ans)
        break

### FIXED CODE ###

N = int(input())
A = [int(input()) for _ in range(N)]
current = 0
visited = {0}
ans = 0

while True:
    current = A[current] - 1
    ans += 1

    if current in visited:
        print(-1)
        break

    if current == 1:
        print(ans)
        break

    visited.add(current)
### BUGGY CODE ###

#UnionFind木とそれを利用したクラスカル法
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
        return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
                x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def nums(self,x):
        return abs(self.parents[self.find(x)])

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


N = int(input())
A = [list(map(int, input().split()))+[i] for i in range(N)]
edge = []
A.sort()
for i in range(N-1):
    w = A[i+1][0]-A[i][0]
    edge.append((w,A[i][2],A[i+1][2]))
A.sort(key=lambda x:x[1])
for i in range(N-1):
    w = A[i+1][1]-A[i][1]
    edge.append((w,A[i][2],A[i+1][2]))

edge.sort()

uf = UnionFind(N)
ans = 0
for i in range(len(edge)):
    u,x,y = edge[i]
    if not uf.same(x,y):
        uf.union(x,y)
        ans += u
print(ans)

### FIXED CODE ###

#最小全域木問題、プリム法
from heapq import *
def solve():
    N = int(input())
    A = [list(map(int, input().split()))+[i] for i in range(N)]
    edge = [[] for _ in range(N)]
    A.sort()
    for i in range(N-1):
        w = min(abs(A[i+1][0]-A[i][0]),abs(A[i+1][1]-A[i][1]))
        edge[A[i][2]].append((w,A[i+1][2]))
        edge[A[i+1][2]].append((w,A[i][2]))
    A.sort(key=lambda x:x[1])
    for i in range(N-1):
        w = min(abs(A[i+1][0]-A[i][0]),abs(A[i+1][1]-A[i][1]))
        edge[A[i][2]].append((w,A[i+1][2]))
        edge[A[i+1][2]].append((w,A[i][2]))
    bridges = []
    heapify(bridges)
    used = [False]*N
    used[0] = True
    ans = 0
    for w,v in edge[0]:
        heappush(bridges,(w,v))
    while len(bridges)>0:
        w,v = heappop(bridges)
        if used[v]==False:
            ans += w
            used[v] = True
            for w,u in edge[v]:
                if used[u]==False:
                    heappush(bridges,(w,u))
    return ans
print(solve())
### BUGGY CODE ###

s,c = map(int,input().split(" "))



counter = 0


while True:
    if c >= 2 and s >= 1:
        s -= 1
        c -= 2
        counter += 1
    if s == 0 and c >= 2:
        c -= 2
        s += 1
    if s == 0 and c <= 1:
        break


print(counter)




### FIXED CODE ###


n,m=map(int,input().split())
first=min(n,m//2)
n -=first
m-=first*2
second = m//4
print(second+first)
### BUGGY CODE ###

import numpy as np
N, W =map(int, input().split())
weight = [0] * 110
value = [0] * 110
dp = np.zeros(shape=(N + 1, W + 1), dtype = np.int64)
#dp = [[0] * (110) for _ in range(10010)]

for i in range(N):
    weight[i], value[i] = map(int, input().split())

for i in range(N):
    for w in range(W + 1):
        if(w >= weight[i]):
            dp[i + 1][w] = max(dp[i][w - weight[i]] + value[i], dp[i][w])
        else:
            dp[i + 1][w] = dp[i][w]
print(dp[N][W])

### FIXED CODE ###

import numpy as np
N, W = map(int, input().split())
dp = np.zeros(W + 1, dtype = np.int64)

for _ in range(N):
    w,v = map(int, input().split())
    np.maximum(dp[w:], dp[:-w] + v, out=dp[w:])

print(dp[W])
### BUGGY CODE ###

def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import fractions
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

from itertools import permutations
from math import factorial, hypot

S = list(map(int, list(input())))
N = len(S)

dp = [[-1] * (N + 1) for i in range(N + 1)]

def rec(l, r):
    if dp[l][r] != -1:
        return dp[l][r]
    if abs(l - r) <= 1:
        return 0

    res = 0
    if S[l] != S[r - 1] and rec(l + 1, r - 1) == r - l - 2:
        res = r - l
    for i in range(l + 1, r):
        res = max(res, rec(l, i) + rec(i, r))
    dp[l][r] = res
    return res
print(rec(0, N))

### FIXED CODE ###

def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import fractions
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

from itertools import permutations
from math import factorial, hypot

# 結局最後には0の塊か1の塊が残る
S = list(map(int, list(input())))
zerocounter = 0
onecounter = 0
for st in S:
    if st == 0:
        zerocounter += 1
    else:
        onecounter += 1
print(min(zerocounter, onecounter) * 2)
### BUGGY CODE ###

N, K = map(int, input().split())

if N == K:
    print(0)

elif N<K and N<=K-N:
    print(N)

elif N<K and N>K-N:
    print(K-N)

elif N>K:
    k = K
    while N>k:
        k=k+K
    if k-N<N-k/K:
        print(k-N)
    else:
        print(N-k/K)


### FIXED CODE ###

N, K = map(int, input().split())

if N%K == 0:
    print(0)

elif N<K and N<=K-N:
    print(N)

elif N<K and N>K-N:
    print(K-N)

elif N>K:
    if K-(N%K)>N%K:
        print(N%K)
    else:
        print(K-(N%K))