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
#include <iostream>
#include <vector>
using namespace std;

int algorytm(vector<pair<vector<int>, int> >& tasmy) {
    int wynik = 0, x = 0;
    do {
        int i = 0;
        while (tasmy[i].first.size() != 0) {
            pair<vector<int>, int> tmp = tasmy[i];
            tasmy[i].second = (tasmy[i].second + 1) % tasmy[i].first.size();
            if (tasmy[i].second == 1) x++;
            else if (tasmy[i].first.size() > 1 && tasmy[i].second == 0) x--;
            i = tmp.first[tmp.second];

        }
        wynik++;
    } while (x > 0);
    return wynik;
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin >> n;
    vector<pair<vector<int>, int> > tasmy;
    tasmy.resize(n);
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        for (int j = 0; j < x; j++) {
            int y;
            cin >> y;
            tasmy[i].first.push_back(y - 1);
            tasmy[i].second = 0;
        }
    }
    cout << algorytm(tasmy);
}