#include using namespace std; const int MX = (1<<20); int T , n , arr[MX] , D; vector < int > v; bool ok; long long solve(){ long long sum = 0; vector < pair < int , int > > v1 , v2; for(int j = 0 ; j < v.size() ; j++) sum += v[j]; if((sum % v.size())) { ok = 0; return 0; } sum /= (v.size()); for(int j = 0 ; j < v.size() ; j++){ if(v[j] < sum) v1.push_back({sum - v[j] , j}); else v2.push_back({v[j] - sum , j}); } reverse(v1.begin() , v1.end()); reverse(v2.begin() , v2.end()); long long ret = 0; while(!v1.empty()){ int x = min(v1.back().first , v2.back().first); ret += 1ll * x * abs(v2.back().second - v1.back().second); v1.back().first -= x; v2.back().first -= x; if(v1.back().first == 0) v1.pop_back(); if(v2.back().first == 0) v2.pop_back(); } return ret; } int main(){ scanf("%d",&T); while(T--){ scanf("%d %d",&n,&D); ok = 1; long long ans = 0; for(int j = 0 ; j < n ; j++) scanf("%d",&arr[j]); for(int j = 0 ; j < D ; j++){ v.clear(); for(int i = j ; i < n ; i+=D){ v.push_back(arr[i]); } ans += solve(); } if(!ok) puts("-1"); else cout<