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
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
#include <algorithm>
#include <cassert>
#include <deque>
#include <iostream>
#include <limits>
#include <utility>
#include <vector>

template <typename Collection>
void printCollection(const Collection& collection)
{
    for (int i = 0; i < collection.size(); i++) {
        std::cout << collection[i];
        if (i < collection.size() - 1) {
            std::cout << " ";
        }
    }
    std::cout << "\n";
}

class Platform
{
   public:
    //    ID notation: <1;100>; 0 means no further platforms
    explicit Platform(std::vector<int> v) : _nextPlatforms(std::move(v)) {}

    // ID notation: <0;99> -1 means no further platforms
    int getNextPlatform()
    {
        if (_nextPlatforms.empty()) {
            return -1;
        }
        const int id = _nextId++;
        if (_nextId >= _nextPlatforms.size()) {
            _nextId = 0;
        }
        return _nextPlatforms[id] - 1;
    }

    bool isStartState() const { return _nextId == 0; }

   private:
    std::vector<int> _nextPlatforms{};
    int _nextId{0};
};

// rows in range <1;500>
// cols in range <1;500>
// moves string size in range <1;300000>
std::vector<Platform> getInput()
{
    int n;
    std::cin >> n;
    std::vector<Platform> input;
    input.reserve(n);
    for (int i = 0; i < n; ++i) {
        int p;
        std::cin >> p;
        std::vector<int> vec(p);
        for (int j = 0; j < p; ++j) {
            std::cin >> vec[j];
        }
        input.emplace_back(Platform(std::move(vec)));
    }
    return input;
    // return v;

    // return {{'.', '.', '.', '.', '.'},
    //         {'.', 'B', '.', 'C', '.'},
    //         {'.', '.', 'C', '.', '.'},
    //         {'.', '.', '.', 'B', '.'}};
}

void print(std::vector<Platform>& platforms)
{
    std::cout << platforms.size() << "\n";
    for (auto& platform : platforms) {
        do {
            std::cout << platform.getNextPlatform() + 1 << " ";
        } while (!platform.isStartState());
    }
}

void travel(std::vector<Platform>& platforms)
{
    for (int i = 0; i != -1;) {
        i = platforms[i].getNextPlatform();
    }
}

int main()
{
    // input
    auto platforms = getInput();
    int count{0};
    do {
        travel(platforms);
        ++count;
    } while (!std::all_of(platforms.begin(), platforms.end(), [](auto& platform) {
        return platform.isStartState();
    }));

    // output
    // printBoard(board);
    // print(platforms);
    std::cout << count << "\n";

    // TESTS
}