/* -*- coding: utf-8 -*- * * 2501.cc: No.2501 Maximum Inversion Number - yukicoder */ #include #include using namespace std; /* constant */ const int MAX_N = 200000; /* typedef */ using ll = long long; /* global variables */ int ls[MAX_N], rs[MAX_N], cs0[MAX_N], cs1[MAX_N]; /* subroutines */ ll calc(int n, int k, int *cs = cs0) { ll sum = 0; for (int i = 0; i < n; i++) { cs[i] = (k < ls[i]) ? ls[i] : (k > rs[i]) ? rs[i] : k; sum += cs[i]; } return sum; } /* main */ int main() { int tn; scanf("%d", &tn); while (tn--) { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) scanf("%d", ls + i); for (int i = 0; i < n; i++) scanf("%d", rs + i); ll lsum = 0, rsum = 0; for (int i = 0; i < n; i++) lsum += ls[i], rsum += rs[i]; if (lsum > m || rsum < m) { puts("-1"); continue; } int k0 = 0, k1 = 1000000000 + 1; while (k0 + 1 < k1) { int k = (k0 + k1) / 2; if (calc(n, k) >= m) k1 = k; else k0 = k; } ll s0 = calc(n, k0, cs0); ll s1 = calc(n, k1, cs1); //printf(" %d,%lld %d,%lld\n", k0, s0, k1, s1); for (int i = 0; s1 > m && i < n; i++) if (cs0[i] < cs1[i]) cs1[i]--, s1--; ll sum = 0, f = 0; for (int i = n - 1; i >= 0; i--) { sum += f * cs1[i]; f += cs1[i]; } printf("%lld\n", sum); } return 0; }