1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <ios>
#include <iostream>
#include <vector>

int read_int() {
  int x;
  std::cin >> x;
  return x;
}

std::vector<int> read_vector(int n) {
  std::vector<int> result(n);
  for (int i = 0; i < n; ++i) {
    std::cin >> result[i];
    result[i]--;
  }
  return result;
}

void process(const std::vector<std::vector<int>> &connections,
             std::vector<int> &state) {
  int index = 0;
  while (connections[index].size() != 0) {
    int next = connections[index][state[index]];
    state[index] = (state[index] + 1) % connections[index].size();
    index = next;
  }
}

int main() {
  std::ios::sync_with_stdio(false);

  const int N = read_int();
  const std::vector<int> ZEROS(N, 0);

  std::vector<std::vector<int>> connections(N);
  std::vector<int> state(N, 0);
  int count = 0;

  for (int i = 0; i < N; ++i) {
    int temp;
    std::cin >> temp;
    connections[i] = read_vector(temp);
  }

  do {
    count++;
    process(connections, state);
  } while (state != ZEROS);

  std::cout << count << std::endl;
  return 0;
}