fork download
  1. #define _GLIBCXX_FILESYSTEM
  2. #include <bits/stdc++.h>
  3. #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  4. #define ll long long
  5. #define f first
  6. #define s second
  7.  
  8. using namespace std;
  9.  
  10.  
  11. int n;
  12.  
  13. int main()
  14. {
  15.  
  16.  
  17. IOS
  18. int t;
  19. cin>>t;
  20. while(t--)
  21. {
  22. int k;
  23. cin>>n>>k;
  24. vector<int> vec(n+1);
  25. for(int i=1; i<=n; i++)
  26. cin>>vec[i];
  27. if(n==1)
  28. {
  29. cout<<0<<"\n";
  30. continue;
  31. }
  32.  
  33. sort(vec.begin()+1,vec.end());
  34.  
  35. ll out=LLONG_MAX;
  36. for(int j=1; j<=n; j++)
  37. {
  38. map<int,int> mp;
  39. int mtch=0;
  40. ll ans=0;
  41. for(int i=1; i<=n; i++)
  42. {
  43. if(i==j&&n&1)continue;
  44. ll md=vec[i]%k;
  45. if(mp[md]==0)
  46. {
  47. mp[md]=i;
  48. mtch++;
  49. }
  50. else
  51. {
  52. ll clc=abs(vec[mp[md]]-vec[i])/k;
  53. ans+=clc;
  54. mp[md]=0;
  55. mtch--;
  56. }
  57. }
  58. if(mtch==0)
  59. out=min(out,ans);
  60.  
  61. if(n&1==0) break;
  62.  
  63. }
  64.  
  65. if(out==LLONG_MAX)cout<<"-1\n";
  66. else cout<<out<<"\n";
  67.  
  68.  
  69.  
  70. }
  71.  
  72.  
  73. }
  74.  
  75.  
  76.  
Success #stdin #stdout 0.01s 5276KB
stdin
11
1 1000000000
1
2 1
624323799 708290323
3 1
3 2 1
4 1
7 1 5 3
5 1
11 2 15 7 10
7 1
1 8 2 16 8 16 31
13 1
2 1 1 3 3 11 12 22 45 777 777 1500 74
10 2
1 2 1 2 1 2 1 2 1 2
11 2
1 2 1 2 1 2 1 2 1 2 1
13 3
2 3 9 14 17 10 22 20 18 30 1 4 28
5 1
2 3 5 3 5
stdout
0
83966524
1
4
6
1
48
-1
0
14
0