-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
63 lines (47 loc) · 1.51 KB
/
Copy pathsolution.java
File metadata and controls
63 lines (47 loc) · 1.51 KB
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
class Solution {
int minOperations(int[] b) {
final int MOD = 1000000007;
int n = b.length;
// Keeps track of visited indices
boolean[] vis = new boolean[n];
// Maximum exponent required for every prime
HashMap<Integer, Integer> map = new HashMap<>();
// Find every cycle
for (int i = 0; i < n; i++) {
if (vis[i])
continue;
int cur = i;
int len = 0;
// Traverse current cycle
while (!vis[cur]) {
vis[cur] = true;
cur = b[cur] - 1;
len++;
}
// Prime factorization of cycle length
int x = len;
for (int p = 2; p * p <= x; p++) {
if (x % p == 0) {
int cnt = 0;
while (x % p == 0) {
x /= p;
cnt++;
}
map.put(p, Math.max(map.getOrDefault(p, 0), cnt));
}
}
// Remaining prime factor
if (x > 1)
map.put(x, Math.max(map.getOrDefault(x, 0), 1));
}
long ans = 1;
// Construct LCM modulo MOD
for (Integer prime : map.keySet()) {
int exp = map.get(prime);
while (exp-- > 0) {
ans = (ans * prime) % MOD;
}
}
return (int) ans;
}
}