N, K = gets.split.take(2).map(&:to_i) Monsters = N.times.map{ gets.split.take(3).map(&:to_i) } Spells = K.times.map{ gets.split.take(5).map(&:to_i) } M = 1001 cusums = (M + 1).times.map { [0] * (M + 1) } # 座標ごとの総ダメージの累積和 Spells.each{|spell| x, y, w, h, d = spell x += 500 y += 500 xx = [M, x + w + 1].min yy = [M, y + h + 1].min cusums[x][y] += d cusums[xx][yy] += d cusums[xx][y] -= d cusums[x][yy] -= d } M.times{|x| M.times{|y| cusums[x][y + 1] += cusums[x][y] } } M.times{|y| M.times{|x| cusums[x + 1][y] += cusums[x][y] } } # 残り体力の合計 ans = 0 Monsters.each{|monster| x, y, hp = monster x += 500 y += 500 ans += [0, hp - cusums[x][y]].max } p ans