1+ // link : https://codeforces.com/contest/1777/submission/356090789
2+
3+ #include < bits/stdc++.h>
4+ using namespace std ;
5+
6+ #define fastio ios::sync_with_stdio (false ); cin.tie(NULL );
7+
8+ using ll = long long ;
9+ using vi = vector<int >;
10+
11+ void solve () {
12+ int n, m;
13+ cin >> n >> m;
14+
15+ vi a (n);
16+ for (int i = 0 ; i < n; i++) cin >> a[i];
17+
18+ sort (a.begin (), a.end ());
19+
20+ vi cnt (m + 1 , 0 );
21+ int covered = 0 ;
22+
23+ auto add = [&](int x) {
24+ for (int d = 1 ; d * d <= x; d++) {
25+ if (x % d == 0 ) {
26+ if (d <= m) {
27+ if (cnt[d] == 0 ) covered++;
28+ cnt[d]++;
29+ }
30+ int other = x / d;
31+ if (other != d && other <= m) {
32+ if (cnt[other] == 0 ) covered++;
33+ cnt[other]++;
34+ }
35+ }
36+ }
37+ };
38+
39+ auto remove = [&](int x) {
40+ for (int d = 1 ; d * d <= x; d++) {
41+ if (x % d == 0 ) {
42+ if (d <= m) {
43+ cnt[d]--;
44+ if (cnt[d] == 0 ) covered--;
45+ }
46+ int other = x / d;
47+ if (other != d && other <= m) {
48+ cnt[other]--;
49+ if (cnt[other] == 0 ) covered--;
50+ }
51+ }
52+ }
53+ };
54+
55+ ll ans = LLONG_MAX;
56+ int l = 0 ;
57+
58+ for (int r = 0 ; r < n; r++) {
59+ add (a[r]);
60+
61+ while (covered == m) {
62+ ans = min (ans, (ll)a[r] - a[l]);
63+ remove (a[l]);
64+ l++;
65+ }
66+ }
67+
68+ if (ans == LLONG_MAX) cout << -1 << ' \n ' ;
69+ else cout << ans << ' \n ' ;
70+ }
71+
72+ int main () {
73+ fastio
74+
75+ int t;
76+ cin >> t;
77+ while (t--) {
78+ solve ();
79+ }
80+ return 0 ;
81+ }
82+
83+
84+ /*
85+
86+ Approach:
87+ - Sort the students by smartness.
88+ - Use a sliding window (two pointers) on the sorted array.
89+ - A student with smartness x covers all topics T ≤ m such that T divides x.
90+ - Maintain a count array for topics and a variable tracking how many topics
91+ are currently covered.
92+ - Expand the right pointer to add students, and once all topics are covered,
93+ shrink from the left to minimize the smartness difference.
94+
95+ Complexity:
96+ - Time: O(n log n + n√max(a))
97+ - Space: O(m)
98+
99+ */
0 commit comments