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

namespace {
    using std::cin;
    using std::cout;
    using std::move;
    using line_t = std::vector<size_t>;
    using element_t = std::pair<size_t, line_t>;
    using system_t = std::vector<element_t>;

    void deliver_suitcase(system_t & platforms, size_t & not_zeros) {
        size_t pos = 0, new_pos;
        while (platforms[pos].second.size() > 0) {
            new_pos = platforms[pos].second[platforms[pos].first] - 1;
            if (platforms[pos].first++ == 0)
                ++not_zeros;
            if (platforms[pos].first == platforms[pos].second.size()) {
                platforms[pos].first = 0;
                --not_zeros;
            }
            pos = new_pos;
        }
    }
}

int main() {
    size_t n, r;
    cin >> n;
    system_t platforms(n);
    for (size_t i = 0; i < n; ++i) {
        cin >> r;
        line_t line(r);
        for (size_t k = 0; k < r; ++k) {
            cin >> line[k];
        }
        platforms[i] = {0, move(line)};
    }

    size_t suitcase = 0;
    size_t not_zeros = 0;
    do {
        deliver_suitcase(platforms, not_zeros);
        ++suitcase;
    } while (not_zeros > 0);

    cout << suitcase << '\n';
    return 0;
}