import sys from itertools import permutations import heapq from collections import deque import random input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) def brute(n,m,L,R): if m < sum(L) or sum(R) < m: return -1 cnt = [L[i] for i in range(n)] while sum(cnt) < m: mini = 10**10 arg = -1 for i in range(n): if cnt[i]!=R[i] and cnt[i] < mini: mini = cnt[i] arg = i cnt[arg] += 1 res = m * (m-1)//2 for i in range(n): res -= cnt[i] * (cnt[i]-1) //2 return res def solve(n,m,L,R): if m < sum(L) or sum(R) < m: return -1 cnt = [L[i] for i in range(n)] rest = m - sum(cnt) def cond(k): check = 0 for i in range(n): if L[i] <= k: check += min(k,R[i]) - L[i] return check <= rest ok = min(L) ng = max(R) + 1 while ng-ok>1: mid = (ok+ng)//2 if cond(mid): ok = mid else: ng = mid for i in range(n): if L[i] <= ok: cnt[i] = min(R[i],ok) rest = m - sum(cnt) idx = [i for i in range(n)] idx.sort(key=lambda i:cnt[i]) for i in idx: if rest and cnt[i]!=R[i]: cnt[i] += 1 rest -= 1 res = m * (m-1)//2 for i in range(n): res -= cnt[i] * (cnt[i]-1) //2 return res while False: n = random.randint(1,10) m = random.randint(1,100) L = [random.randint(1,m) for i in range(n)] R = [random.randint(L[i],m) for i in range(n)] if solve(n,m,L,R) != brute(n,m,L,R): print(n,m) print(L) print(R) print(solve(n,m,L,R),brute(n,m,L,R)) exit() print("AC") for _ in range(int(input())): n,m = mi() L = li() R = li() print(solve(n,m,L,R))