-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrongTask632D.java
More file actions
99 lines (92 loc) · 2.97 KB
/
wrongTask632D.java
File metadata and controls
99 lines (92 loc) · 2.97 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
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
import java.util.*; import java.math.*;
public class wrongTask632D {
private static Res[] cache = null;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, m;
n = s.nextInt();
m = s.nextInt();
long[] arr = new long[n];
cache = new Res[n];
for(int i = 0; i < arr.length; i++) {
arr[i] = s.nextInt();
}
Res rmax = null;
int e = -1;
for(int i = 0; i < arr.length; i++) {
Res rs = lcmi(arr, i, m);
if(rmax == null || rmax.max < rs.max) {
e = i;
rmax = rs;
}
}
long ml = rmax.resByMl.stream().map(p -> p.x).min(Long::compare).get();
List<Integer> path = new ArrayList<>();
if(rmax != null)
path.add(e);
Res p = lcmi(arr, e, m);
while(p.i != -1) {
path.add(p.i);
p = lcmi(arr, p.i, m);
}
System.out.println(ml + " " + rmax.max);
Integer[] pathInt = path.stream().map(i -> i + 1).toArray(size -> new Integer[size]);
Arrays.sort(pathInt);
for(int i = 0; i < pathInt.length; i++) {
System.out.print( pathInt[i] + " ");
}
System.out.println("");
}
private static Res lcmi(long[] arr, int n, int m) {
if(cache[n] != null) {
return cache[n];
}
Res cur = new Res(-1, -1);
if(arr[n] <= m) {
cur = new Res(1, -1);
cur.resByMl.add(new Pair<Long, Pair<Res, Long>>(arr[n], null));
}
for(int i = 0; arr[n] <= m && i < n; i++) {
Res r = lcmi(arr, i, m);
if(r.max != -1 && r.max + 1 >= cur.max) {
for(Pair<Long, Pair<Res, Long>> prml: r.resByMl) {
if(lcm(prml.x, arr[n]) <= m) {
if(r.max + 1 > cur.max) {
cur = new Res(r.max + 1, i);
}
cur.resByMl.add(new Pair<Long, Pair<Res, Long>>(lcm(prml.x, arr[n]), new Pair<Res,Long>(r, prml.x)));
}
}
}
}
cache[n] = cur;
return cur;
}
private static long gcd(long a, long b) {
BigInteger aa = BigInteger.valueOf(a);
BigInteger bb = BigInteger.valueOf(b);
return aa.gcd(bb).longValue();
}
private static long lcm(long a, long b) {
if(a == 0 || b == 0)
throw new RuntimeException("Can't compute lcm(" + a + ", " + b + ")");
return (a * b) / gcd(a, b);
}
private static class Res {
int max;
int i;
List<Pair<Long, Pair<Res, Long>>> resByMl = new ArrayList<>();
public Res(int max, int i) {
this.max = max;
this.i = i;
}
}
private static class Pair<U, V> {
U x;
V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
}
}