n = gets.to_i
a = Array.new(360, 0)
n.times do
    m, d, v, s = gets.split.map(&:to_i)
    from = 30 * (m - 1) + (d - 1)
    to = (from + v - 1) % 360
    i = from
    loop do
        j = i % 360
        dist =  from - i
        break if j == to || dist == s
        a[j] = s - dist if a[j] < s - dist
        i -= 1
    end
    i = to
    loop do
        j = i % 360
        dist = i - to
        break if j == from || dist == s
        a[j] = s - dist if a[j] < s - dist
        i += 1
    end
    i = from
    loop do
        j = i % 360
        a[j] = s if a[j] < s
        break if j == to
        i += 1
    end
end
p a.min

