We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<iostream>#include<vector>usingnamespacestd;vector<int>absolutePermutation(intn,intk){vector<int>result;// If k is 0, the permutation is just the natural numbers from 1 to n.if(k==0){for(inti=1;i<=n;++i){result.push_back(i);}returnresult;}// If n is not divisible by 2 * k, a valid permutation is not possible.if(n%(2*k)!=0){return{-1};}// Construct the permutation in groups of 2 * k.for(inti=1;i<=n;i+=2*k){// Add the first k numbers in the group shifted by +k.for(intj=0;j<k;++j){result.push_back(i+j+k);}// Add the next k numbers in the group shifted by -k.for(intj=0;j<k;++j){result.push_back(i+j);}}returnresult;}intmain(){intt;cin>>t;// Number of querieswhile(t--){intn,k;cin>>n>>k;vector<int>result=absolutePermutation(n,k);if(result.size()==1&&result[0]==-1){cout<<"-1\n";}else{for(intnum:result){cout<<num<<" ";}cout<<"\n";}}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Absolute Permutation
You are viewing a single comment's thread. Return to all comments →