Untitled
unknown
c_cpp
10 months ago
1.9 kB
10
Indexable
#include <bits/stdc++.h>
using namespace std;
int solve(int n, int m, vector<int> smart){
//precomputing all the factors. Storing the factors of smart[i] in a map
unordered_map<int, vector<int>>factors;
for(int i=0; i < smart.size(); i++){
if(smart[i]<=m)factors[smart[i]].push_back(smart[i]);
for(int j=1; j<=smart[i]/2 && j<=m; j++){
if(smart[i]%j==0){
factors[smart[i]].push_back(j);
}
}
}
//mfreq[i](where 1<=i<=m) is the number of multiples of i between left and right
unordered_map<int, int>mfreq;
sort(smart.begin(), smart.end());
int ans=INT32_MAX;
int left=0;
int enter=0;
for(int right=0; right < n; right++){
for(int i=1; i<=m;i++){
if(i<=smart[right] && smart[right]%i==0) mfreq[i]++;
}
while(mfreq.size()==m){
enter=1;
int count=0;
vector<int>v = factors[smart[left]];
//if all factors of smart[left] are in the map with frequency >1 then incrememnt left and decrement the map
for(int i=0; i < v.size(); i++){
if(mfreq[v[i]] > 1){
count++;
}
}
if(count==v.size()){
for(int i=0; i < v.size(); i++){
mfreq[v[i]]--;
}
left++;
}
else{
ans = min(ans, right-left);
break;
}
}
}
if(enter==0)return -1; //if size of map is never equal to m then no solution
return ans;
}
int main(){
int t;
cin >> t;
while(t--){
int n, m;
cin >> n >> m;
vector<int> smart;
for(int i=0; i < n; i++){
int k;
cin >> k;
smart.push_back(k);
}
cout << solve(n,m,smart) << endl;
}
}Editor is loading...
Leave a Comment