#include #include int cmp_int_rev (const void *ap, const void *bp) { int a = *(int *)ap; int b = *(int *)bp; if (a < b) { return 1; } if (a > b) { return -1; } return 0; } void upheap (int q[][2], int idx) { int pidx = (idx-1)/2; if (idx > 0 && q[pidx][0] > q[idx][0]) { int s = q[idx][0]; q[idx][0] = q[pidx][0]; q[pidx][0] = s; s = q[idx][1]; q[idx][1] = q[pidx][1]; q[pidx][1] = s; upheap(q, pidx); } return; } void downheap (int q[][2], int idx, int size) { int ch[2] = { 1000000001, 1000000001 }; int chidx = -1; if (2*idx+1 < size) { ch[0] = q[2*idx+1][0]; } if (2*idx+2 < size) { ch[1] = q[2*idx+2][0]; } if (ch[1] < ch[0] && ch[1] < q[idx][0]) { chidx = 2*idx+2; } else if (ch[0] < q[idx][0]) { chidx = 2*idx+1; } if (chidx > 0) { int s = q[idx][0]; q[idx][0] = q[chidx][0]; q[chidx][0] = s; s = q[idx][1]; q[idx][1] = q[chidx][1]; q[chidx][1] = s; downheap(q, chidx, size); } return; } void dequeue (int q[][2], int *size, int *res) { res[0] = q[0][0]; res[1] = q[0][1]; if (*size > 0) { *size -= 1; q[0][0] = q[*size][0]; q[0][1] = q[*size][1]; downheap(q, 0, *size); } return; } int main () { int t = 0; int n = 0; int m = 0; int lr[200000][2] = {}; int res = 0; long long a[200000] = {}; int q[200000][2] = {}; res = scanf("%d", &t); while (t > 0) { long long lsum = 0LL; long long rsum = 0LL; res = scanf("%d", &n); res = scanf("%d", &m); for (int i = 0; i < n; i++) { res = scanf("%d", lr[i]); lsum += (long long)lr[i][0]; } for (int i = 0; i < n; i++) { res = scanf("%d", lr[i]+1); rsum += (long long)lr[i][1]; } if (lsum > (long long)m || rsum < (long long)m) { printf("-1\n"); } else { int qsize = 0; int idx = 0; long long ans = 0LL; int tmpsum = 0; qsort(lr, n, sizeof(int)*2, cmp_int_rev); while (idx < n && m > tmpsum && 1+(m-tmpsum-1)/(n-idx) <= lr[idx][0]) { a[idx] = (long long)lr[idx][0]; tmpsum += lr[idx][0]; idx++; } for (int i = idx; i < n; i++) { q[qsize][0] = lr[i][1]; q[qsize][1] = i; upheap(q, qsize); qsize++; } while (qsize > 0) { int tmp[2] = {}; if (idx > 0 && 1+(m-tmpsum-1)/qsize >= (int)a[idx-1]) { idx--; tmpsum -= (int)a[idx]; a[idx] = 0LL; q[qsize][0] = lr[idx][1]; q[qsize][1] = idx; upheap(q, qsize); qsize++; } dequeue(q, &qsize, tmp); if (tmp[0] < (m-tmpsum)/(qsize+1)) { a[tmp[1]] = (long long)tmp[0]; tmpsum += tmp[0]; } else { a[tmp[1]] = (long long)((m-tmpsum)/(qsize+1)); tmpsum += (m-tmpsum)/(qsize+1); } } for (int i = 0; i < n; i++) { ans += a[i]*(((long long)m)-a[i]); } ans /= 2LL; printf("%lld\n", ans); } t--; } return 0; }