1+ /*
2+ Submission link: https://codeforces.com/contest/1777/submission/356097157
3+ - Tc: O(n log n + n√max(a))
4+ - Sc: O(m)
5+
6+ Approach :
7+ Sort the students by smartness so they are in increasing order.
8+ Use two pointers to form a window of students, adding one student at a time from the right.
9+ Each student can cover some topics, and we keep track of which topics are covered inside the window.
10+ When all topics are covered, try removing students from the left to make the smartness difference as small as possible.
11+ */
12+
13+ #include < iostream>
14+ #include < vector>
15+ #include < algorithm>
16+
17+ using namespace std ;
18+ const int MAXA = 100005 ;
19+ vector<int > divisors[MAXA];
20+ void precompute () {
21+ for (int i = 1 ; i < MAXA; i++) {
22+ for (int j = i; j < MAXA; j += i) {
23+ divisors[j].push_back (i);
24+ }
25+ }
26+ }
27+
28+ void solve () {
29+ int n, m;
30+ cin >> n >> m;
31+ vector<int > a (n);
32+ for (int i = 0 ; i < n; i++) cin >> a[i];
33+
34+ sort (a.begin (), a.end ());
35+
36+ vector<int > count (m + 1 , 0 );
37+ int covered_topics = 0 ;
38+ int min_diff = 1e9 ;
39+ int left = 0 ;
40+
41+ for (int right = 0 ; right < n; right++) {
42+ for (int d : divisors[a[right]]) {
43+ if (d > m) break ;
44+ if (count[d] == 0 ) covered_topics++;
45+ count[d]++;
46+ }
47+ while (covered_topics == m) {
48+ min_diff = min (min_diff, a[right] - a[left]);
49+
50+ for (int d : divisors[a[left]]) {
51+ if (d > m) break ;
52+ count[d]--;
53+ if (count[d] == 0 ) covered_topics--;
54+ }
55+ left++;
56+ }
57+ }
58+
59+ if (min_diff == 1e9 ) cout << -1 << " \n " ;
60+ else cout << min_diff << " \n " ;
61+ }
62+
63+ int main () {
64+ precompute ();
65+
66+ int t;
67+ cin >> t;
68+ while (t--) {
69+ solve ();
70+ }
71+ return 0 ;
72+ }
0 commit comments