|
| 1 | +// submission: https://codeforces.com/contest/1777/submission/356260631 |
| 2 | + |
| 3 | +/* Given n students of a school and m topics 1,2,3,…,m from which the quiz questions will be formed. |
| 4 | +The i-th student is considered proficient in a topic T if (ai%T)=0. |
| 5 | +Otherwise, he is a rookie in that topic. We are asked to find the team formation of any no. of students |
| 6 | +such that for every topic there is a member of the team proficient in this topic. Whilst minimizing the |
| 7 | +maximum difference between the smartness of any two students and output this difference */ |
| 8 | + |
| 9 | +#include <bits/stdc++.h> |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +using ll = long long; |
| 13 | +#define all(x) (x).begin(), (x).end() |
| 14 | + |
| 15 | +const int MOD = 1e9 + 7; // 998244353 |
| 16 | +const ll INF = 1e18; |
| 17 | +const int maxval=100005; |
| 18 | +vector<int> divisors[maxval]; |
| 19 | + |
| 20 | +void precompute(){ |
| 21 | + for(int i=1;i<maxval;i++){ |
| 22 | + for(int j=i;j<maxval;j+=i) divisors[j].push_back(i); |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +void solve() { |
| 27 | + int n,m; |
| 28 | + cin>>n>>m; |
| 29 | + vector<int> a(n); |
| 30 | + for(auto &x: a) cin>>x; |
| 31 | + sort(all(a)); |
| 32 | + int cov_topics=0, min_dif=INT_MAX, l=0;//left |
| 33 | + vector<int> cnt(m+1,0); |
| 34 | + |
| 35 | + //we take 2 pointers left and right |
| 36 | + for(int r=0;r<n;r++){ |
| 37 | + // Add current student's topics to the window |
| 38 | + for(int topic: divisors[a[r]]){ |
| 39 | + if(topic>m) break; //since divisors[] also keeps sorted divisors, if one is greater than m, then all subsequent will be so |
| 40 | + if(cnt[topic]==0) cov_topics++; //increment cov_topics for every unique topic |
| 41 | + cnt[topic]++; |
| 42 | + } |
| 43 | + |
| 44 | + /* While covered_topics == m (i.e., the team is valid): |
| 45 | + Update the minimum difference: ans = min(ans, a[right] - a[left]). |
| 46 | + Move the left pointer forward to try and shrink the window. |
| 47 | + Remove the left student's factors from the count.*/ |
| 48 | + while(cov_topics==m){ |
| 49 | + min_dif=min(min_dif,a[r]-a[l]); |
| 50 | + for(int topic: divisors[a[l]]){ |
| 51 | + if(topic>m) break; |
| 52 | + cnt[topic]--; |
| 53 | + if(cnt[topic]==0) cov_topics--; |
| 54 | + } |
| 55 | + l++; |
| 56 | + } |
| 57 | + } |
| 58 | + if(min_dif==INT_MAX) cout<<-1<<endl; //means no team can cover all the m topics |
| 59 | + else cout<<min_dif<<endl; |
| 60 | + |
| 61 | +} |
| 62 | + |
| 63 | +int main() { |
| 64 | + // Fast I/O |
| 65 | + ios::sync_with_stdio(false); |
| 66 | + cin.tie(nullptr); |
| 67 | + precompute(); |
| 68 | + int t; |
| 69 | + cin >> t; |
| 70 | + while (t--) { |
| 71 | + solve(); |
| 72 | + } |
| 73 | + |
| 74 | + return 0; |
| 75 | +} |
0 commit comments