import std/[strutils, sequtils] proc mwf(n0, m0, a0, b0, c0, d0: int64): int64 = ## Max Weighted Floor (MWF) assert n0 > 0 and m0 > 0 and c0 >= 0 and c0 < m0 and d0 >= 0 and d0 < m0 var n = n0 var m = m0 var a = a0 var b = b0 var c = c0 var d = d0 var sumAcc: int64 = 0 var maxAcc: int64 = (d div m) * b while true: var q: int64 var cand: int64 (q, c) = (c div m, c mod m) a += b * q (q, d) = (d div m, d mod m) sumAcc += b * q if sumAcc > maxAcc: maxAcc = sumAcc let n1 = n - 1 let yMax = (c * n1 + d) div m if yMax == 0: cand = sumAcc + a * n1 if cand > maxAcc: maxAcc = cand return maxAcc if a >= 0: cand = sumAcc + a * n1 + b * yMax if cand > maxAcc: maxAcc = cand else: sumAcc += a + b n = yMax d = m - d - 1 swap(a, b) swap(c, m) when isMainModule: let t = stdin.readLine.parseInt for _ in 0..