#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int b[N], a[N], f1[N], f2[N], n, m;
long long Ans;
int pd(int x) {
  priority_queue<int> p, q;
  Ans = 0;
  int cnt = 0;
  for (int i = n; i; i--) {
    q.push(x - b[i]);
    int v1 = p.empty() ? -(1 << 30) : p.top(), v2 = q.top();
    if (v1 < v2) {
      if (a[i] < v2) {
        cnt++;
        p.push(a[i]);
        q.pop();
        Ans += a[i] - v2;
      }
    } else if (a[i] < v1) {
      p.pop();
      p.push(a[i]);
      Ans += a[i] - v1;
    }
  }
  return cnt <= m;
}
signed main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
  int l = 0, r = 2e9;
  while (l < r) {
    int mid = ((long long)l + r + 1) / 2;
    if (pd(mid))
      l = mid;
    else
      r = mid - 1;
  }
  pd(l);
  printf("%lld\n", Ans + (long long)m * l);
}

### Prompt

Develop a solution in Cpp to the problem described below:

The plans for HC2 are rather far-fetched: we are just over 500 000 days away from HC2 3387, for example, and accordingly we are planning to have a couple hundred thousand problems in that edition (we hope that programming contests will become wildly more popular). The marmots need to get to work, and they could use a good plan...

Input

Same as the medium version, but the limits have changed: 1 ≤ k ≤ n ≤ 500 000.

Output

Same as the medium version.

Example

Input

8 4
3 8 7 9 9 4 6 8
2 5 9 4 3 8 9 1


Output

32

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int b[N], a[N], f1[N], f2[N], n, m;
long long Ans;
int pd(int x) {
  priority_queue<int> p, q;
  Ans = 0;
  int cnt = 0;
  for (int i = n; i; i--) {
    q.push(x - b[i]);
    int v1 = p.empty() ? -(1 << 30) : p.top(), v2 = q.top();
    if (v1 < v2) {
      if (a[i] < v2) {
        cnt++;
        p.push(a[i]);
        q.pop();
        Ans += a[i] - v2;
      }
    } else if (a[i] < v1) {
      p.pop();
      p.push(a[i]);
      Ans += a[i] - v1;
    }
  }
  return cnt <= m;
}
signed main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
  int l = 0, r = 2e9;
  while (l < r) {
    int mid = ((long long)l + r + 1) / 2;
    if (pd(mid))
      l = mid;
    else
      r = mid - 1;
  }
  pd(l);
  printf("%lld\n", Ans + (long long)m * l);
}

```