Problem:
 Score : 400 points    Problem Statement There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.  Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min} , where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min} .      Constraints  2 ≤ H, W ≤ 10^5         Input Input is given from Standard Input in the following format:  H  W       Output Print the minimum possible value of S_{max} - S_{min} .        Sample Input 1 3 5      Sample Output 1 0  In the division below, S_{max} - S_{min} = 5 - 5 = 0 .          Sample Input 2 4 5      Sample Output 2 2  In the division below, S_{max} - S_{min} = 8 - 6 = 2 .          Sample Input 3 5 5      Sample Output 3 4  In the division below, S_{max} - S_{min} = 10 - 6 = 4 .          Sample Input 4 100000 2      Sample Output 4 1       Sample Input 5 100000 100000      Sample Output 5 50000

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache






MOD = 10**9+7
INF = float('inf')






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)



def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





H,W = IL()

ans = INF
for i in range(1,H):
  a = i*W
  if H-i>=2:
    b = ((H-i)//2)*W
    c = -(-(H-i)//2)*W
    ans = min(ans,max(a,b,c)-min(a,b,c))
  if W >= 2:
    b = (W//2)*(H-i)
    c = -(-W//2)*(H-i)
    ans = min(ans,max(a,b,c)-min(a,b,c))
for i in range(1,W):
  a = i*H
  if W-i>=2:
    b = ((W-i)//2)*H
    c = -(-(W-i)//2)*H
    ans = min(ans,max(a,b,c)-min(a,b,c))
  if H >= 2:
    b = (H//2)*(W-i)
    c = -(-H//2)*(W-i)
    ans = min(ans,max(a,b,c)-min(a,b,c))
print(ans)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache






MOD = 10**9+7
INF = float('inf')






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)



def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





H,W = IL()

ans = INF
for i in range(1,H):
  a = i*W
  if H-i>=2:
    b = ((H-i)//2)*W
    c = (H-i)*W-b
    ans = min(ans,max(a,b,c)-min(a,b,c))
  if W >= 2:
    b = (W//2)*(H-i)
    c = (H-i)*W-b
    ans = min(ans,max(a,b,c)-min(a,b,c))
for i in range(1,W):
  a = i*H
  if W-i>=2:
    b = ((W-i)//2)*H
    c = (W-i)*H-b
    ans = min(ans,max(a,b,c)-min(a,b,c))
  if H >= 2:
    b = (H//2)*(W-i)
    c = (W-i)*H-b
    ans = min(ans,max(a,b,c)-min(a,b,c))
print(ans)

Solution (Python):
def aaa(a, b):
    return abs((a // 3 * b) - ((a // 3 + 1) * b))


def bbb(a, b):
    ret = 1000 * 100
    for x in range(1, a):
        xx = a - x
        i = x * b
        j = xx * (b // 2)
        k = xx * (b // 2 + (b % 2))
        tmp = max(abs(i - j), abs(j - k), abs(k - i))
        ret = min(ret, tmp)
    return ret


H, W = map(int, input().split())

if H % 3 == 0 or W % 3 == 0:
    print(0)
else:
    a = aaa(H, W)
    b = aaa(W, H)
    c = bbb(H, W)
    d = bbb(W, H)
    print(min(a, b, c, d))

Solution (Python):
from math import floor, ceil
H, W = map(int, input().split())

ans = float('inf')
for h in range(1, H+1):
    A = h * W
    B = floor((H-h) / 2) * W
    C = ceil((H-h) / 2) * W
    B2 = (H-h) * floor(W / 2)
    C2 = (H-h) * ceil(W / 2)
    ans = min(ans, max([A, B, C]) - min([A, B, C]))
    ans = min(ans, max([A, B2, C2]) - min([A, B2, C2]))

for w in range(1, W+1):
    A = H * w
    B = floor((W-w) / 2) * H
    C = ceil((W-w) / 2) * H
    B2 = (W-w) * floor(H / 2)
    C2 = (W-w) * ceil(H / 2)
    ans = min(ans, max([A, B, C]) - min([A, B, C]))
    ans = min(ans, max([A, B2, C2]) - min([A, B2, C2]))

print(ans)

Solution (Python):


import sys






























def main():
    mod = 1000000007                
    inf = float('inf')              
    
    sys.setrecursionlimit(10**6)    
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    def calc_T_form(h, w):
        left = w // 2
        right = w - left
        ans = inf
        for i in range(1, h):
            sa, sb, sc = i * w, (h-i) * left, (h-i) * right
            ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
        return ans
    
    def calc_rotateT_form(h, w):
        up = h // 2
        down = h - h//2
        ans = inf
        for i in range(1, w):
            sa, sb, sc = i * h, (w-i) * up, (w-i) * down
            ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
        return ans
    
    def calc_slice(h, w):
        return min((h//3+1)*w - (h//3)*w, (w//3+1)*h - (w//3)*h)

    
    h, w = mi()
    if h * w % 3 == 0:
        print(0)
    else:
        print(min(calc_T_form(h, w), calc_rotateT_form(h, w), calc_slice(h, w)))



if __name__ == "__main__":
    main()

Solution (Python):
def pattern1(A, B):
    s1 = (A // 3) * B
    s2 = ((A - (A // 3)) // 2) * B
    s3 = A * B - s1 - s2
    return max([abs(s1 - s2), abs(s2 - s3), abs(s3 - s1)])


def pattern2(A, B):
    a1 = A // 2
    a2 = A - a1
    b1 = (2 * B + 1) // 3
    b2 = B - b1
    s1, s2, s3 = a1 * b1, a2 * b1, A * b2
    return max([abs(s1 - s2), abs(s2 - s3), abs(s3 - s1)])


def main():
    H, W = list(map(int, input().split(' ')))
    ans = min([
        pattern1(H, W),
        pattern1(W, H),
        pattern2(H, W),
        pattern2(W, H)
    ])
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
h,w=map(int,input().split())
if h%3==0 or w%3==0:
  print(0)
else:
  temp=[w,h]
  if h%2==0 and w%2==0:
    temp.append(abs(int(w//3+1)*h-int(w-w//3-1)*int(h//2)))
    temp.append(abs(int(w//3)*h-int(w-w//3)*int(h//2)))        
    temp.append(abs(int(h//3+1)*w-int(h-h//3-1)*int(w//2)))
    temp.append(abs(int(h//3)*w-int(h-h//3)*int(w//2)))  
  elif h%2==0:
    temp.append(max(int(h//3*w),int(h-h//3)*int(w//2),int(h-h//3)*int(w//2+1))-min(int(h//3*w),int(h-h//3)*int(w//2),int(h-h//3)*int(w//2+1)))
    temp.append(max(int(h//3+1)*w,int(h-h//3-1)*int(w//2),int(h-h//3-1)*int(w//2+1))-min(int(h//3+1)*w,int(h-h//3-1)*int(w//2),int(h-h//3-1)*int(w//2+1)))
    temp.append(abs(int(w//3+1)*h-int(w-w//3-1)*int(h//2)))
    temp.append(abs(int(w//3)*h-int(w-w//3)*int(h//2)))             
  elif w%2==0:
    temp.append(max(int(w//3*h),int(w-w//3)*int(h//2),int(w-w//3)*int(h//2+1))-min(int(w//3*h),int(w-w//3)*int(h//2),int(w-w//3)*int(h//2+1)))
    temp.append(max(int(w//3+1)*h,int(w-w//3-1)*int(h//2),int(w-w//3-1)*int(h//2+1))-min(int(w//3+1)*h,int(w-w//3-1)*int(h//2),int(w-w//3-1)*int(h//2+1)))
    temp.append(abs(int(h//3+1)*w-int(h-h//3-1)*int(w//2)))
    temp.append(abs(int(h//3)*w-int(h-h//3)*int(w//2)))                
  else:
    temp.append(max(int(h//3*w),int(h-h//3)*int(w//2),int(h-h//3)*int(w//2+1))-min(int(h//3*w),int(h-h//3)*int(w//2),int(h-h//3)*int(w//2+1)))
    temp.append(max(int(h//3+1)*w,int(h-h//3-1)*int(w//2),int(h-h//3-1)*int(w//2+1))-min(int(h//3+1)*w,int(h-h//3-1)*int(w//2),int(h-h//3-1)*int(w//2+1)))
    temp.append(max(int(w//3*h),int(w-w//3)*int(h//2),int(w-w//3)*int(h//2+1))-min(int(w//3*h),int(w-w//3)*int(h//2),int(w-w//3)*int(h//2+1)))
    temp.append(max(int(w//3+1)*h,int(w-w//3-1)*int(h//2),int(w-w//3-1)*int(h//2+1))-min(int(w//3+1)*h,int(w-w//3-1)*int(h//2),int(w-w//3-1)*int(h//2+1)))
  print(min(temp))

Solution (Python):



def main():
    H, W = map(int, input().split())
    if H % 3 == 0 or W % 3 == 0:
        print(0)
    else:
        ans = min(W,H)

        
        for i in range(3):
            d = (H // 3)- 1 + i
            if d > 0:
                choco = [d * W, (H-d) * (W//2), (H-d) * (W - W//2)]
                ans = min(ans, max(choco) - min(choco))
        
        
        for i in range(3):
            d = (W // 3)- 1 + i
            if d > 0:
                choco = [d * H, (W-d) * (H//2), (W-d) * (H - H//2)]
                ans = min(ans, max(choco) - min(choco))
        
        print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 5 + 10)


def input(): return sys.stdin.readline().strip()


def resolve():
    def main():
        H, W = map(int, input().split())
        if H % 3 == 0 or W % 3 == 0:
            return 0
        else:
            ans = 10**18

            for h in range(H):
                A = h*W
                B = ((H-h)//2)*W
                C = (H-h-(H-h)//2)*W
                ans = min(max(A, B, C) -
                          min(A, B, C), ans)

                B = (W//2)*(H-h)
                C = (W-(W//2))*(H-h)
                ans = min(max(A, B, C) -
                          min(A, B, C), ans)

            for w in range(W):
                A = w*H
                B = ((W-w)//2)*H
                C = (W-w-(W-w)//2)*H
                ans = min(max(A, B, C) -
                          min(A, B, C), ans)

                B = (H//2)*(W-w)
                C = (H-(H//2))*(W-w)
                ans = min(max(A, B, C) -
                          min(A, B, C), ans)
            return ans
    print(main())


resolve()

Solution (Python):
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


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 size(self, x):
        return -self.parents[self.find(x)]

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

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

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

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

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

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True




def warshall_floyd(d, n):
    
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d



def dijkstra_heap(s, edge, n):
    
    d = [10**20] * n
    used = [True] * n 
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d


def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr


def lcm(x, y):
    return (x * y) // gcd(x, y)


def lcm_list(numbers):
    return reduce(lcm, numbers, 1)


def gcd_list(numbers):
    return reduce(gcd, numbers)






def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P


def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret



h, w = map(int, input().split())

ans1 = INF
ans2 = INF
ans3 = INF
ans4 = INF

if h % 3 == 0:
    ans1 = 0
else:
    ans1 = w

if w % 3 == 0:
    ans2 = 0
else:
    ans2 = h

for i in range(1, w):
    if h % 2 == 0:
        ans3 = min(ans3, abs(h * i - (w - i) * h // 2))
    else:
        a = h * i
        b = (w - i) * (h // 2)
        c = (w - i) * (-(-h // 2))
        ans3 = min(ans3, max(a, b, c) - min(a, b, c))

for i in range(1, h):
    if w % 2 == 0:
        ans3 = min(ans3, abs(w * i - (h - i) * w // 2))
    else:
        a = w * i
        b = (h - i) * (w // 2)
        c = (h - i) * (-(-w // 2))
        ans3 = min(ans3, max(a, b, c) - min(a, b, c))

ans = min(ans1, ans2, ans3, ans4)
print(ans)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    H, W = map(int, input().split())

    if H % 3 == 0 or W % 3 == 0:
        print(0)
        exit()

    res = f_inf
    for h in range(H):
        A = h * W

        B = W * ((H - h) // 2)
        C = W * ((H - h) - (H - h) // 2)
        ma = max(A, B, C)
        mi = min(A, B, C)
        res = min(res, ma - mi)

        B = (H - h) * (W // 2)
        C = (H - h) * (W - W // 2)
        ma = max(A, B, C)
        mi = min(A, B, C)
        res = min(res, ma - mi)

    for w in range(W):
        A = w * H

        B = H * ((W - w) // 2)
        C = H * ((W - w) - (W - w) // 2)
        ma = max(A, B, C)
        mi = min(A, B, C)
        res = min(res, ma - mi)

        B = (W - w) * (H // 2)
        C = (W - w) * (H - H // 2)
        ma = max(A, B, C)
        mi = min(A, B, C)
        res = min(res, ma - mi)

    print(res)


if __name__ == '__main__':
    resolve()

Solution (Python):
H, W = map(int, input().split())
ans = H*W

if(W%3 == 0):
  ans = 0
else:
  ans = min(ans, H)


if(H%3 == 0):
  ans = 0
else:
  ans = min(ans, W)
  

if(H % 2 == 0):
  sa = W*H//2
  sb = W*H//2
  sc = 0
  ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
  for i in range(W-1):
    sc += H
    sa -= H//2
    sb -= H//2
    ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
else:
  sa = W * (H//2)
  sb = W * (H//2 + 1)
  sc = 0
  ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
  for i in range(W-1):
    sc += H
    sa -= H//2
    sb -= H//2 + 1
    ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
    

if(W % 2 == 0):
  sa = W*H//2
  sb = W*H//2
  sc = 0
  ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
  for i in range(H-1):
    sc += W
    sa -= W//2
    sb -= W//2
    ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
else:
  sa = H * (W//2)
  sb = H * (W//2 + 1)
  sc = 0
  ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
  for i in range(W-1):
    sc += W
    sa -= W//2
    sb -= W//2 + 1
    ans = min(ans, max(sa, sb, sc) - min(sa, sb, sc))
    
print(ans)

Solution (Python):
h, w = map(int, input().split())

ans = 10 ** 10
for i in range(h):
    x = (i + 1) * w
    mid = (h - i - 1) // 2
    y = mid * w
    z = (h - i - 1 - mid) * w
    ans = min(ans, max(x, y, z) - min(x, y, z))

    mid = w // 2
    y = (h - i - 1) * mid
    z = (h - i - 1) * (w - mid)
    ans = min(ans, max(x, y, z) - min(x, y, z))

for j in range(w):
    x = (j + 1) * h
    mid = (w - j - 1) // 2
    y = mid * h
    z = (w - j - 1 - mid) * h
    ans = min(ans, max(x, y, z) - min(x, y, z))

    mid = h // 2
    y = (w - j - 1) * mid
    z = (w - j - 1) * (h - mid)
    ans = min(ans, max(x, y, z) - min(x, y, z))

print(ans)

Solution (Python):
h,w = map(int,input().split())
ans = 10**10

def menseki(h,w):
    global ans
    for i in range(1,h):
        
        haba = w//2
        ans = min(ans,max(i*w,haba*(h-i),(w-haba)*(h-i))-min(i*w,haba*(h-i),(w-haba)*(h-i)))
        
        if i == h-1:
            continue
        tate = (h-i)//2
        ans = min(ans,max(w*i,tate*w,(h-i-tate)*w)-min(w*i,tate*w,(h-i-tate)*w))

menseki(h,w)
menseki(w,h)

print(ans)

Solution (Python):

import re
import math
from collections import defaultdict
from collections import deque
import collections
from fractions import Fraction
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache

readline=sys.stdin.readline
sys.setrecursionlimit(2000000)

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    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 ispow(a,b):
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
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,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    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
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
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(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def pm(x):
    return x//abs(x)
def inputintlist():
    return list(map(int,input().split()))


H,W=inputintlist()
ans=inf
for a in range(1,H):
    A=a*W
    
    B=((H-a)//2)*W
    C=H*W-A-B
    ans=min(ans,max([A,B,C])-min([A,B,C]))
    
    
    B=(W//2)*(H-a)
    C=H*W-A-B
    ans=min(ans,max([A,B,C])-min([A,B,C]))
    
H,W=W,H
for a in range(1,H):
    A=a*W
    
    B=((H-a)//2)*W
    C=H*W-A-B
    ans=min(ans,max([A,B,C])-min([A,B,C]))
    
    
    B=(W//2)*(H-a)
    C=H*W-A-B
    ans=min(ans,max([A,B,C])-min([A,B,C]))
    

print(ans)

Solution (Python):
H, W = map(int, input().split())
if (H%3) * (W%3) == 0:
  print(0)
  quit()

ans = min(H, W)
w1 = W // 2
w2 = W - w1
S1 = (H - 1) * w1
S2 = (H - 1) * w2
S3 = W
for i in range(H-1):
  diff = max(S1, S2, S3) - min(S1, S2, S3)
  ans = min(ans, diff)
  S1 -= w1; S2 -= w2; S3 += W

h1 = H // 2
h2 = H - h1
S1 = (W - 1) * h1
S2 = (W - 1) * h2
S3 = H
for i in range(W-1):
  diff = max(S1, S2, S3) - min(S1, S2, S3)
  ans = min(ans, diff)
  S1 -= h1; S2 -= h2; S3 += H

print(ans)

Solution (Python):
H, W = map(int, input().split())
if (H%3) * (W%3) == 0:
  print(0)
  quit()

ans = H * W
w1 = W // 2
w2 = W - w1
S1 = (H - 1) * w1; T1 = W * ((H-1)//2)
S2 = (H - 1) * w2; T2 = W * (H-1) - T1
S3 = W
h = H - 1
for i in range(H-1):
  diff1 = max(S1, S2, S3) - min(S1, S2, S3)
  diff2 = max(T1, T2, S3) - min(T1, T2, S3)
  ans = min(ans, diff1, diff2)
  S1 -= w1; S2 -= w2; S3 += W
  h -= 1
  T1 = W * (h//2)
  T2 = W*h - T1

h1 = H // 2
h2 = H - h1
S1 = (W - 1) * h1; T1 = H * ((W-1)//2)
S2 = (W - 1) * h2; T2 = H * (W-1) - T1
S3 = H
w = W - 1
for i in range(W-1):
  diff1 = max(S1, S2, S3) - min(S1, S2, S3)
  diff2 = max(T1, T2, S3) - min(T1, T2, S3)
  ans = min(ans, diff1, diff2)
  S1 -= h1; S2 -= h2; S3 += H
  w -= 1
  T1 = H * (w//2)
  T2 = H*w - T1

print(ans)

Solution (Python):

import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    H,W=map(int,input().split())
    ans=INF
    for i in range(1,H):
        S0=W*i
        S1=(H-i)*(W//2)
        S2=(H-i)*(-(-W//2))
        S3=W*((H-i)//2)
        S4=W*(-((i-H)//2))
        ans=min(ans,max(abs(S0-S1),abs(S0-S2)),max(abs(S0-S3),abs(S0-S4)))
    for i in range(1,W):
        S0=H*i
        S1=(W-i)*(H//2)
        S2=(W-i)*(-(-H//2))
        S3=H*((W-i)//2)
        S4=H*(-((i-W)//2))
        ans=min(ans,max(abs(S0-S1),abs(S0-S2)),max(abs(S0-S3),abs(S0-S4)))
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
def solve():
    H,W = map(int,input().split())
    
    ans = float('inf')
    a = 0
    b = 0
    c = 0

    for h in range(H+1):
        if W % 2 == 0:
            a = h * W // 2
            b = h * W // 2
        else:
            a = h * (W-1) // 2
            b = h * (W+1) // 2
        c = W * (H-h)

        s_max = max(a,b,c)
        s_min = min(a,b,c)
        ans = min(ans, s_max-s_min)

        a = h * W
        if (H-h) % 2 == 0:
            b = (H-h) // 2 * W
            c = (H-h) // 2 * W
        else:
            b = (H-h-1) // 2 * W
            c = (H-h+1) // 2 * W
        
        s_max = max(a,b,c)
        s_min = min(a,b,c)
        ans = min(ans, s_max-s_min)

    for w in range(W+1):
        if H % 2 == 0:
            a = w * H // 2
            b = w * H // 2
        else:
            a = w * (H-1) // 2
            b = w * (H+1) // 2
        c = H * (W-w)

        s_max = max(a,b,c)
        s_min = min(a,b,c)
        ans = min(ans, s_max-s_min)

        a = w * H
        if (W-w) % 2 == 0:
            b = (W-w) // 2 * H
            c = (W-w) // 2 * H
        else:
            b = (W-w-1) // 2 * H
            c = (W-w+1) // 2 * H
        
        s_max = max(a,b,c)
        s_min = min(a,b,c)
        ans = min(ans, s_max-s_min)
    
    print(ans)

if __name__ == '__main__':
    solve()

Solution (Python):
H, W = map(int, input().split())

def case1(h, w):
    MIN = float('inf')
    for i in range(1, h):
        sa = i * w
        sb = (h - i) * (w//2)
        sc = (h - i) * (w - w//2)
        if max([sa,sb,sc]) - min([sa,sb,sc]) < MIN:
            MIN = max([sa,sb,sc]) - min([sa,sb,sc]) 
    return MIN

def case2(h, w):
    MIN = float('inf')
    for i in range(1, h):
        sa = i * w
        sb = (h - i)//2 * w
        sc = (h - i -(h - i)//2) * w
        if max([sa,sb,sc]) - min([sa,sb,sc]) < MIN:
            MIN = max([sa,sb,sc]) - min([sa,sb,sc]) 
    return MIN
print(min([case1(H,W) , case1(W,H), case2(H,W), case2(W,H)]))

Solution (Python):
H, W = map(int, input().split())

ans = float("inf")
for h, w in zip([H, W], [W, H]):
    
    for ah in range(1, h):
        
        Sa = ah * w
        bw = (w - 1) // 2 + 1
        Sb = (h - ah) * bw
        Sc = (h - ah) * (w - bw)
        ans = min(ans, (max(Sa, Sb, Sc)-min(Sa, Sb, Sc)))

        
        if (h - ah) > 1:
            bh = ((h - ah) - 1) // 2 + 1
            Sb = bh * w
            Sc = (h - ah - bh) * w
            ans = min(ans, (max(Sa, Sb, Sc)-min(Sa, Sb, Sc)))
        
print(ans)

Solution (Python):
h, w = map(int, input().split())
if not h%3 or not w%3:
  print(0)
else:
  ans = min([h, w])
  for i in range(h):
    sub = max([abs(w*i-w//2*(h-i)), abs(w*i-(w-w//2)*(h-i))])
    if ans > sub:
      ans = sub
  for i in range(w):
    sub = max([abs(h*i-h//2*(w-i)), abs(h*i-(h-h//2)*(w-i))])
    if ans > sub:
      ans = sub
  print(ans)

Solution (Python):
H,W = map(int,input().split())

ans = 1e19

for i in range(1,H):
    tate = W*i
    
    if i < H-1:
        mini = W*((H-i)//2)
        
        ans = min(ans,max(tate,mini,H*W-mini-tate)-min(tate,mini,H*W-mini-tate))

    
    mini = (H-i)*(W//2)
    
    ans = min(ans,max(tate,mini,H*W-tate-mini)-min(tate,mini,H*W-tate-mini))


for i in range(1,W):
    yoko = H*i
    if i < W-1:
        mini = H*((W-i)//2)
        
        ans = min(ans,max(yoko,mini,H*W-mini-yoko)-min(yoko,mini,H*W-yoko-mini))
    mini = (W-i)*(H//2)
    
    ans = min(ans,max(yoko,mini,H*W-yoko-mini)-min(yoko,mini,H*W-yoko-mini))

print(ans)