def _min(a,b);a < b ? a : b; end N = gets.to_i S = gets.chomp.chars A = gets.split.map(&:to_i) dp = Array.new(N + 1, Float::INFINITY) ndp = Array.new(N + 1, Float::INFINITY) dp[0] = 0 S.zip(A) do |s,a| (0 .. N).each do |d| if s == ?( ndp[d + 1] = _min(dp[d], ndp[d + 1]) if d + 1 <= N ndp[d - 1] = _min(dp[d] + a, ndp[d - 1]) if d - 1 >= 0 else ndp[d + 1] = _min(dp[d] + a, ndp[d + 1]) if d + 1 <= N ndp[d - 1] = _min(dp[d], ndp[d - 1]) if d - 1 >= 0 end end ndp, dp = dp, ndp ndp.fill(Float::INFINITY) end puts dp[0]