def eating_time(i)
  17*(i%2) + 3*(i%3) + 19
end

def have_seats(guest_n, seats)
  _seats = seats
  loop do
    first = _seats.index(nil)
    return false if first.nil?
    enough_seats = _seats[first, guest_n]
    if enough_seats.all?(&:nil?) && enough_seats.size == guest_n
      return first
    end
    _seats = [first+1..-1]
  end
end

readlines.each do |l|
  n = l.to_i
  seats = Array.new(17,nil)
  line = []
  etimes = []
  wtimes = []
  time = 0 
  i = 0

  while true
    if !(leaving_guest = etimes.index(time)).nil?
      seats.map! do |seat|
        if seat == leaving_guest
          nil
        else
          seat
        end
      end
    end
    
    if line.any?
      0.upto(line.size-1) { |j| line[j][1] += 1 }
    end
    
    if (time%5).zero?
      line << [i, 0]
      i += 1
    end
    
    before_s = -1
    while line.any?  
      s = line.first.first
      break if before_s == s
      guest_n = (s % 5 == 1 ? 5 : 2)
      if (first = have_seats(guest_n, seats))
        seats[first, guest_n] = [s]*guest_n
        etimes[s] = eating_time(s) + time
        wtimes[s] = line.first.last
        line.shift
      end
      before_s = s
    end

    if seats.include?(n)
      puts wtimes[n]
      break
    end

    time += 1
  end
end