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
#include<iostream>
#include<vector>

int n;
std::vector<std::vector<int> > G;

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);

    std::cin >> n;
    for (int i = 0; i < n; i++) {
        std::vector<int> v;
        int k;
        std::cin >> k;
        for (int j = 0; j < k; j++) {
            int u;
            std::cin >> u;
            v.push_back(u - 1);
        }
        G.push_back(v);
    }

    int state[n];
    for (int i = 0; i < n; i++) {
        state[i] = 0;
    }

    int i = 0;
    while(true) {
        int p = 0;
        i += 1;
        while(G[p].size() > 0) {
            int next_p = G[p][state[p]];
            state[p] = (state[p] + 1) % G[p].size();
            p = next_p;
        }

        bool done = true;
        for (int j = 0; j < n; j++) {
            if (state[j] != 0) {
                done = false;
                break;
            }
        }

        if (done) {
            break;
        }
    }

    std::cout << i << "\n";

    return 0;
}