#include #include #include #include using namespace std; using ll = long long; using P = pair; int main() { int T; cin >> T; while (T--) { ll N, M; cin >> N >> M; vector L(N), R(N); for (int i = 0; i < N; i++) cin >> L[i]; for (int i = 0; i < N; i++) cin >> R[i]; ll sum_L = 0, sum_R = 0; for (int i = 0; i < N; i++) sum_L += L[i]; for (int i = 0; i < N; i++) sum_R += R[i]; if (M < sum_L || sum_R < M) { cout << -1 << endl; continue; } ll ok = 1e9, ng = 0; while (ok - ng > 1) { ll mid = (ok + ng) / 2; ll sum = 0; for (int i = 0; i < N; i++) { if (mid > R[i]) sum += R[i]; else if (mid <= L[i]) sum += L[i]; else sum += mid; } if (sum >= M) ok = mid; else ng = mid; } ll sum = 0; for (int i = 0; i < N; i++) { if (ok > R[i]) sum += R[i]; else if (ok <= L[i]) sum += L[i]; else sum += ok; } int cnt = 0; vector A; for (int i = 0; i < N; i++) { if (ok > R[i]) A.push_back(R[i]); else if (ok <= L[i]) A.push_back(L[i]); else { if (cnt < sum - M) A.push_back(ok - 1); else A.push_back(ok); cnt++; } } ll ans = M * (M - 1) / 2; for (auto a: A) ans -= a * (a - 1) / 2; cout << ans << endl; } }