#include #include #include #include #include #include #include #include std::int64_t NChoose2(const int n) { return std::int64_t{n} * (n - 1) / 2; } // // \sum_{i = 1}^n R_i = m のとき -1 を出力する。 std::int64_t Solve(const int m, const std::vector& l, const std::vector& r) { const int n = l.size(); assert(std::ssize(r) == n); if (std::reduce(r.begin(), r.end(), INT64_C(0)) == m) return -1; // ここ std::vector order(n * 2); std::iota(order.begin(), order.end(), 0); std::ranges::stable_sort( order, {}, [n, &l, &r](const int i) -> int { return i < n ? l[i] : r[i - n]; }); assert(order.back() >= n); std::int64_t length = std::reduce(l.begin(), l.end(), INT64_C(0)); if (length > m) return -1; std::int64_t ans = std::transform_reduce( l.begin(), l.end(), INT64_C(0), std::plus(), NChoose2); if (length == m) return NChoose2(m) - ans; int optional_values = 0; for (int i = 0; i < n * 2; ++i) { if (order[i] < n) { const int index = order[i]; length -= l[index]; ans -= NChoose2(l[index]); ++optional_values; } else { const int index = order[i] - n; length += r[index]; assert(length <= m); ans += NChoose2(r[index]); --optional_values; } if (i + 1 < n * 2) { const int next_v = (order[i + 1] < n ? l[order[i + 1]] : r[order[i + 1] - n]); if (length + std::int64_t{next_v} * optional_values >= m) { assert(optional_values > 0); const int t0 = (m - length + optional_values - 1) / optional_values - 1; assert((order[i] < n ? l[order[i]] : r[order[i] - n]) <= t0 && t0 < next_v); const int num_of_t0 = (t0 + 1) * optional_values - (m - length); assert(0 <= num_of_t0 && num_of_t0 < optional_values); ans += NChoose2(t0) * num_of_t0; ans += NChoose2(t0 + 1) * (optional_values - num_of_t0); return NChoose2(m) - ans; } } } assert(length == std::reduce(r.begin(), r.end(), INT64_C(0)) && length < m); return -1; } 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; }