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
54
55
56
57
58
59
#include <iostream>
#include <vector>

using namespace std;
using ll = long long;

const int MAX_N = 107;

int n;
vector<int> graph[MAX_N];
ll state[MAX_N];

void init() {
    cin >> n;

    for (int i = 1; i <= n; i++) {
        int m;
        cin >> m;

        for (int j = 0; j < m; j++) {
            int v;
            cin >> v;

            graph[i].push_back(v);
        }
    }
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    init();

    ll result = 0;
    ll reset = n;

    do {
        result++;
        int v = 1;

        while (graph[v].size() > 0) {
            int u = v;
            v = graph[v][state[v]];
            int ps = state[u];
            state[u] = (state[u] + 1) % graph[u].size();

            if (ps > 0 && state[u] == 0)
                reset++;
            else if (ps == 0 && state[u] == 1)
                reset--;
        }
    } while (reset < n);

    cout << result << '\n';

    return 0;
}