1+ /*
2+
3+ Link: https://codeforces.com/contest/1777/submission/356094799
4+
5+ Approach:
6+ we dont care about duplicates, so keep unique
7+ it is a sliding window problem, we sort them based on their smartness, and have a precomuted array of factors
8+ we go through each one of them, and see if we cover all the topics...
9+ if we do, we start removing the students to the left side... if less, then add from right side
10+
11+ */
12+
13+ #include < bits/stdc++.h>
14+ using namespace std ;
15+
16+ const int MAX_N = 1e5 + 5 ;
17+ vector<vector<int >> factors (MAX_N);
18+
19+ void generateFactors () {
20+ for (int x = 2 ; x < MAX_N; x++) {
21+ for (int y = x; y < MAX_N; y += x) {
22+ factors[y].push_back (x);
23+ }
24+ }
25+ }
26+
27+ void solve () {
28+ int n, m;
29+ cin >> n >> m;
30+ vector<int > a (n);
31+ for (auto &x: a) cin >> x;
32+
33+ vector<int > curr (m+1 );
34+ int cnt = 0 ;
35+
36+ if (m == 1 ) {
37+ cout << 0 << endl;
38+ return ;
39+ }
40+
41+ sort (a.begin (), a.end ());
42+ // cout << "sorted a\n";
43+ auto it = std::unique (a.begin (), a.end ());
44+ a.erase (it, a.end ());
45+
46+ n = a.size ();
47+
48+ int l = 0 , r = 0 , best = INT_MAX;
49+ while (r < n) {
50+ // cout << "l, r: " << l << " " << r << endl;
51+ for (auto factor: factors[a[r]]) {
52+ if (factor > m) break ;
53+ if (curr[factor] == 0 ) cnt++;
54+ curr[factor]++;
55+ }
56+ while (cnt == m-1 ) {
57+ best = min (best, a[r] - a[l]);
58+ for (auto factor: factors[a[l]]) {
59+ if (factor > m) break ;
60+ curr[factor]--;
61+ if (curr[factor] == 0 ) cnt--;
62+ }
63+ l++;
64+ }
65+ r++;
66+ }
67+
68+ // for (auto x: a) cout << x << " ";
69+ cout << (best == INT_MAX ? -1 : best) << endl;
70+ }
71+
72+ int main () {
73+ generateFactors ();
74+ // cout << "generated factors\n";
75+
76+ int t;
77+ cin >> t;
78+ while (t--) {
79+ // cout << "t: " << t << endl;
80+ solve ();
81+ }
82+ }
0 commit comments