def assert f unless f puts "Error!: Constraint Violation" exit end end h,w,k = gets.split.map(&:to_i) assert(2 <= h && h <= 300) assert(2 <= w && w <= 300) assert(1 <= k && k <= 2**20) a = h.times.map{gets.split.map(&:to_i)} a.each do |row| row.each do |v| assert(1 <= v && v <= 2**20) end end hash = Hash.new(0) 21.times do |i| hash[2**i] = 1 end b = h.times.map{gets.split.map(&:to_i)} b.each do |row| row.each do |v| assert(1 <= v && v <= 2**20) assert(hash[v] == 1) end end sum_row = Array.new(h,0) sum_col = Array.new(w,0) cost_row = Array.new(h){Array.new} cost_col = Array.new(w){Array.new} h.times do |i| w.times do |j| sum_row[i] += a[i][j] cost_row[i] << b[i][j] sum_col[j] += a[i][j] cost_col[j] << b[i][j] end cost_row[i].sort! end w.times do |i| cost_col[i].sort! end # Z を決め打ちした時の部分問題 # (a + b) * (a + c) に対応 def calc(a,b,c,y,z,k) b_opt = (z*(a+c) - y*(a+b) + k) / (2*y) ky = k/y kouho = [0,b_opt,b_opt+1,ky] max = 0 kouho.each do |v| next if v < 0 || ky < v rest_k = k - v*y val = (a+b+v) * (a+c+rest_k/z) max = val if max < val end max end # 三分探索 def solve(x,y,z,x_cost,y_cost,z_cost,k) l = 0 r = k / z_cost while r - l > 2 #精度 dif = (r - l) / 3 t1,t2 = l+dif,r-dif s1 = calc(z+t1,x,y,x_cost,y_cost,k-t1*z_cost) s2 = calc(z+t2,x,y,x_cost,y_cost,k-t2*z_cost) if s1 < s2 #上に凸 l = t1 else r = t2 end end max = 0 3.times do |i| t = l + i next if t*z_cost > k v = calc(z+t,x,y,x_cost,y_cost,k-t*z_cost) max = v if max < v end max end max = 0 h.times do |i| ai = a[i] bi = b[i] cost_rowi = cost_row[i] w.times do |j| z = ai[j] z_cost = bi[j] x = sum_row[i] - z x_cost = z_cost == cost_rowi[0] ? cost_rowi[1] : cost_rowi[0] y = sum_col[j] - z y_cost = z_cost == cost_col[j][0] ? cost_col[j][1] : cost_col[j][0] if x_cost < y_cost x,y = y,x x_cost,y_cost = y_cost,x_cost end v = solve(x,y,z,x_cost,y_cost,z_cost,k) max = v if max < v end end puts max