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
// C5 - Walizki
#include <iostream>
#include <vector>
#include <algorithm>
#include <deque>
using namespace std;

struct Carousel {
	vector<int> routes;
	unsigned long long dividend;
	unsigned long long divisor;
	int r;
	
	Carousel() {
		this->dividend = 0;
		this->divisor = 1;
	}
};

unsigned long long gcd(unsigned long long a, unsigned long long b) {
	if (b == 0) {
		return a;
	}
	return gcd(b, a % b);
}

unsigned long long lcm(unsigned long long a, unsigned long long b) {
	if (a == 0) {
		return b;
	}
	if (b == 0) {
		return a;
	}
	return a / gcd(a, b) * b;
}	

int main() {
	ios_base::sync_with_stdio(0);
	int n, r, a;
	unsigned long long gcdRes, result;
	Carousel *carousels;
	
	cin >> n;
	carousels = new Carousel[n];
	for (int i = 0; i < n; ++i) {
		cin >> r;
		carousels[i].r = r;
		for (int j = 0; j < r; ++j) {
			cin >> a;
			carousels[i].routes.push_back(a - 1);
		}
	}
	
	carousels[0].dividend = 1;
	carousels[0].divisor = 1;
	result = 1;
	
	for (int i = 0; i < n; ++i) {
		if (carousels[i].r == 0) {
			carousels[i].dividend = 0;
		} else {
			carousels[i].divisor *= carousels[i].r;
		}
		gcdRes = gcd(carousels[i].dividend, carousels[i].divisor);
		carousels[i].dividend /= gcdRes;
		carousels[i].divisor /= gcdRes;
		result = lcm(result, carousels[i].divisor);
		for (int j = 0; j < carousels[i].r; ++j) {
				if (carousels[i].dividend > 0) {
					carousels[carousels[i].routes[j]].dividend = carousels[carousels[i].routes[j]].dividend * carousels[i].divisor + carousels[i].dividend * carousels[carousels[i].routes[j]].divisor;
					carousels[carousels[i].routes[j]].divisor *= carousels[i].divisor;
					gcdRes = gcd(carousels[carousels[i].routes[j]].dividend, carousels[carousels[i].routes[j]].divisor);
					carousels[carousels[i].routes[j]].dividend /= gcdRes;
					carousels[carousels[i].routes[j]].divisor /= gcdRes;
			}
		}
	}
	
	cout << result;
	
	delete [] carousels;	
	
	return 0;
}