Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef std::pair<int, int> ipair;
- #define int long long
- #define pb push_back
- #define ff first
- #define ss second
- #define fr(i, j, k) for (int i = j; i < k; i++)
- #define cnt_ones(x) __builtin_popcount(x)
- #define all(x) x.begin(), x.end()
- #define mp make_pair
- #define mod 1000000007
- #define IOS \
- std::ios::sync_with_stdio(false); \
- cin.tie(NULL); \
- cout.tie(NULL);
- int findSmallestRange(vector<vector<int>>b,int k) {
- int i, minval, maxval, minrange, minel, maxel, flag, minind;
- int ptr[k+1];
- // initializing to 0 index;
- for (i = 0; i <= k; i++)
- ptr[i] = 0;
- minrange = INT_MAX;
- while (1) {
- // for mainting the index of list containing the minimum element
- minind = -1;
- minval = INT_MAX;
- maxval = INT_MIN;
- flag = 0;
- // iterating over all the list
- for (i = 0; i < k; i++) {
- // if every element of list[i] is traversed then break the loop
- if (ptr[i] == b[i].size()) {
- flag = 1;
- break;
- }
- // find minimum value among all the list elements pointing by the ptr[]
- // array
- if (ptr[i] < b[i].size() && b[i][ptr[i]] < minval) {
- minind = i; // update the index of the list
- minval = b[i][ptr[i]];
- }
- // find maximum value among all the list elements pointing by the ptr[]
- // array
- if (ptr[i] < b[i].size() && b[i][ptr[i]] > maxval) {
- maxval = b[i][ptr[i]];
- }
- }
- // if any list exhaust we will not get any better answer ,so break the while
- // loop
- if (flag)
- break;
- ptr[minind]++;
- // updating the minrange
- if ((maxval - minval) < minrange) {
- minel = minval;
- maxel = maxval;
- minrange = maxel - minel;
- }
- }
- return minrange;
- }
- void init() {
- int T;
- cin >> T;
- while (T--) {
- int N,M;
- cin>>N>>M;
- vector<vector<int>>b(M);
- vector<int>a(N);
- for(int i=0;i<N;i++) cin>>a[i];
- for(int i=0;i<N;i++)
- b[i%M].pb(a[i]);
- for(int i=0;i<M;i++){
- sort(b[i].begin(),b[i].end());
- }
- int res=findSmallestRange(b,M);
- cout<<res<<endl;
- }
- }
- int32_t main() {
- IOS;
- init();
- return 0;
- }
Add Comment
Please, Sign In to add comment