#include #include #include #include #include #include #include std::int64_t NChoose2(const int n) { return std::int64_t{n} * (n - 1) / 2; } // #890216 ベース // 二分探索の下界の初期値が間違っている。 std::int64_t Solve( int m, const std::vector& l, const std::vector& r) { const int n = l.size(); assert(std::ssize(r) == n); if (std::reduce(l.begin(), l.end(), INT64_C(0)) > m) return -1; int t0 = m + 1; for (int lbound = 1; lbound + 1 < t0;) { // 本来は 0 const int t = std::midpoint(lbound, t0); std::int64_t length = 0; for (int i = 0; i < n; ++i) { length += std::clamp(t, l[i], r[i]); } (length >= m ? t0 : lbound) = t; } if (t0 > m) return -1; std::int64_t ans = NChoose2(m); int num_of_t0 = 0; for (int i = 0; i < n; ++i) { const int c_i = std::clamp(t0, l[i], r[i]); m -= c_i; ans -= NChoose2(c_i); if (l[i] < t0 && t0 <= r[i]) ++num_of_t0; } assert(m <= 0 && -m <= num_of_t0); ans -= (NChoose2(t0 - 1) - NChoose2(t0)) * -m; return ans; } int main() { constexpr int kMaxT = 200000, kMaxN = 200000, kMaxM = 1000000000; int t; std::cin >> t; assert(1 <= t && t <= kMaxT); while (t--) { int n, m; std::cin >> n >> m; assert(1 <= n && n <= kMaxN && 1 <= m && m <= kMaxM); std::vector l(n); for (int i = 0; i < n; ++i) { std::cin >> l[i]; } std::vector r(n); for (int i = 0; i < n; ++i) { std::cin >> r[i]; assert(0 <= l[i] && l[i] <= r[i] && r[i] <= kMaxM); } std::cout << Solve(m, l, r) << '\n'; } return 0; }