Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<pair<long long int,long long int > >vec;
- vector<long long int> mark(100009);
- vector<long long int >sample(100009);
- unordered_map<long long int ,long long int >org;
- /* We would first mark all the vector elements with their respective colors and as for every M elements they are unique
- so it will just repeat as 1,2,3....m,1,2,3... */
- void init(long long int N, long long int M)
- {
- long long int it=1;
- for(long long int i=0;i<N;i++)
- {
- mark[i]=it;
- it++;
- if(it>M)
- {
- it=1;
- }}}
- /* Now I will pair their color with the actual numbers, mark vector can be excluded and this process can be dN in a
- single loop for memory efficiency but I have dN this for simplicity */
- void filling(long long int N)
- {
- for(long long int i=0;i<N;i++)
- {
- vec.push_back(make_pair(sample[i],mark[i]));
- }
- }
- /*Initialsing first k elements in the map to cover cases with k or more than k elements with same value (answer will be 0 in that case)*/
- void gut(long long int M)
- {
- for(long long int i=0;i<M;i++)
- org[vec[i].second]++;
- }
- void solve(long long int N, long long int M)
- {
- long long int final_answer=INT_MAX;
- long long int forv=0; /* first iterator*/
- long long int backw=M-1; /* second iterator*/
- long long int height=0; /* calculating variable*/
- gut(M);
- if(org.size()==M)
- {
- height=vec[backw].first-vec[forv].first;
- final_answer = min(height,final_answer);
- }
- while(1)
- {
- if(org.size()==M)
- {
- long long int height = vec[backw].first-vec[forv].first; /* check for minimum value */
- final_answer=min(final_answer,height);
- org[vec[forv].second]--; /* Now we will increase the first iterator until we get to the point where the map size again becomes<M and that point will be the minimum value */
- if(org[vec[forv].second]==0) org.erase(vec[forv].second); /* once we have one colour completed, we would delete this from the map*/
- forv++;
- }
- else
- {
- backw++; /* we increase the second iterator till we get the map size == M */
- if(backw>vec.size()-1)
- break;
- org[vec[backw].second]++;}} /* also we will keep adding the colour */
- cout << final_answer << endl;
- final_answer=INT_MAX;
- org.clear();
- sample.clear();
- mark.clear();
- vec.clear();
- }
- int main()
- {
- ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
- long long int test;
- cin >> test;
- while(test--)
- {
- long long int N,M;
- cin >> N >> M;
- for(long long int i=0;i<N;i++)
- {
- cin >> sample[i];
- }
- init(N,M);
- filling(N);
- sort(vec.begin(),vec.end()); /* sorting to get the the difference easily as Arr[k]-Arr[0] is always less than Arr[k+1]-Arr[0] */
- vector<long long int >point;
- for(long long int i=0;i<N;i++)
- point.push_back(vec[i].second);
- solve(N,M);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment