gets.to_i.times do a, b, c = gets.split.map(&:to_i) if c == 1 puts -1 next end dfs = Hash.new do |h, n| if n == 0 h[n] = 0 elsif n % c == 0 h[n] = [h[n / c] + b, (n + c - 2) / (c - 1) * b].min else h[n] = [h[n - n % c] + b, (n + c - 2) / (c - 1) * b].min end end puts dfs[a] end