#include using namespace std; void solve() { int 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]; } long long low = accumulate(L.begin(), L.end(), (long long) 0); if(!(low<= (long long) M && (long long) M <= accumulate(R.begin(), R.end(), (long long) 0))) { cout << "-1\n"; return; } if(N == 1) { cout << "0\n"; return; } long long ALL = (long long) M * M; long long ok = 1000000005, ng = *min_element(L.begin(), L.end()) - 1; while(abs(ok - ng) > 1) { long long mid = (ok + ng) >> 1; long long S = 0; for(int i = 0; i < N; i++) { if(mid >= L[i]) { S += min(mid, R[i]) - L[i]; } } if(low + S >= M) { ok = mid; } else { ng = mid; } } vector T(N); vector id; for(int i = 0; i < N; i++) { if(R[i] < ok) { T[i] = R[i]; } else if(L[i] > ok) { T[i] = L[i]; } else { T[i] = ok; id.emplace_back(i); } } long long S = accumulate(T.begin(), T.end(), (long long) 0); if(S > M) { for(int i = 0; i < S - M; i++) { T[id[i]]--; } } else if(M > S) { for(int i = 0; i < M - S; i++) { T[id[i]]++; } } assert(accumulate(T.begin(), T.end(), (long long) 0) == M); for(int i = 0; i < N; i++) { ALL -= T[i] * T[i]; } assert(ALL % 2 == 0); cout << ALL / 2 << '\n'; } int main() { cin.tie(0); cout.tie(0); ios::sync_with_stdio(false); int T; cin >> T; while(T--) { solve(); } return 0; }