File tree Expand file tree Collapse file tree
Problems/Binary-Search/Day-07/sol/suzzzal Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // subission link - https://codeforces.com/contest/1777/submission/356090266
2+
3+
4+ /*
5+ * APPROACH:
6+ * Line up all students from least to most smart. Add them to the team one by one until
7+ * they know all the topics. Once they do, try removing the least smart student to make
8+ * the smartness gap as small as possible while still covering every topic.
9+ */
10+
11+ #include < bits/stdc++.h>
12+
13+ using namespace std ;
14+
15+ const int MAX_VAL = 100005 ;
16+
17+ vector<int > divs[MAX_VAL];
18+
19+ void precompute () {
20+ for (int i = 1 ; i < MAX_VAL; i++) {
21+ for (int j = i; j < MAX_VAL; j += i) {
22+ divs[j].push_back (i);
23+ }
24+ }
25+ }
26+
27+ void solve () {
28+ int n, m;
29+ cin >> n >> m;
30+
31+ vector<int > a (n);
32+ for (int i = 0 ; i < n; i++) {
33+ cin >> a[i];
34+ }
35+
36+ sort (a.begin (), a.end ());
37+
38+ vector<int > freq (m + 1 , 0 );
39+
40+ int covered_cnt = 0 ;
41+ int min_diff = INT_MAX;
42+ int left = 0 ;
43+
44+ for (int right = 0 ; right < n; right++) {
45+ int current_smartness = a[right];
46+
47+ for (int d : divs[current_smartness]) {
48+ if (d > m) continue ;
49+
50+ if (freq[d] == 0 ) {
51+ covered_cnt++;
52+ }
53+ freq[d]++;
54+ }
55+
56+ while (covered_cnt == m) {
57+ min_diff = min (min_diff, a[right] - a[left]);
58+
59+ int remove_smartness = a[left];
60+ for (int d : divs[remove_smartness]) {
61+ if (d > m) continue ;
62+
63+ freq[d]--;
64+ if (freq[d] == 0 ) {
65+ covered_cnt--;
66+ }
67+ }
68+ left++;
69+ }
70+ }
71+
72+ if (min_diff == INT_MAX) {
73+ cout << -1 << endl;
74+ } else {
75+ cout << min_diff << endl;
76+ }
77+ }
78+
79+ int main () {
80+ ios::sync_with_stdio (false );
81+ cin.tie (nullptr );
82+
83+ precompute ();
84+
85+ int t;
86+ cin >> t;
87+ while (t--) {
88+ solve ();
89+ }
90+
91+ return 0 ;
92+ }
You can’t perform that action at this time.
0 commit comments