n = gets.to_i

class Player
  attr_accessor :id, :battle_orders, :possible_game

  def initialize(id, battle_orders)
    @id = id
    @battle_orders = battle_orders
    @possible_game = true
  end

  def next_opponent_id
    battle_orders.first - 1
  end

  def battle
    battle_orders.shift
    self.possible_game = false
  end

  def finish?
    battle_orders.empty?
  end

  def reset
    self.possible_game = true
  end
end

players = []
n.times {|i| players << Player.new(i, gets.split.map(&:to_i))}

day = 0
gamed_players = []
while true
  day += 1
  candidate_players = []
  gamed_players.each {|gamed_player| candidate_players << gamed_player}
  gamed_players = []
  candidate_players = players if day == 1
  candidate_players.each do |player|
    next if player.finish?
    opponent_player = players[player.next_opponent_id]
    next if opponent_player.next_opponent_id != player.id || opponent_player.finish?
    game_pair = [player, opponent_player]
    if game_pair.all?(&:possible_game)
      game_pair.each do |player|
        player.battle
        gamed_players << player
      end
    end
  end
  break if gamed_players.empty?
  gamed_players.each(&:reset)
end

if players.all?(&:finish?)
  p day - 1
else
  p -1
end