Advertisement
savrasov

problem_C

Jun 17th, 2017
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.43 KB | None | 0 0
  1. int a[300000], n, k;
  2.  
  3. int main()
  4. {
  5.     ll ans, s = 0, f = 0;
  6.     cin >> n >> k;
  7.     for (int i = 0; i < n; i++)
  8.         scanf("%d", &a[i]);
  9.     sort(a, a + n);
  10.     for (int i = 0; i < k; i++)
  11.     {
  12.         f += i * 1ll * a[i] - s;
  13.         s += a[i];
  14.     }
  15.     ans = f;
  16.     for (int i = k; i < n; i++)
  17.     {
  18.         s -= a[i - k];
  19.         f -= -(k - 1) * 1ll * a[i - k] + s;
  20.         f += (k - 1) * 1ll * a[i] - s;
  21.         s += a[i];
  22.         ans = min(ans, f);
  23.     }
  24.     cout << ans;
  25.     return 0;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement