You are the head of a large enterprise. $n$ people work at you, and $n$ is odd (i. e. $n$ is not divisible by $2$).

You have to distribute salaries to your employees. Initially, you have $s$ dollars for it, and the $i$-th employee should get a salary from $l_i$ to $r_i$ dollars. You have to distribute salaries in such a way that the median salary is maximum possible.

To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:  the median of the sequence $[5, 1, 10, 17, 6]$ is $6$,  the median of the sequence $[1, 2, 1]$ is $1$. 

It is guaranteed that you have enough money to pay the minimum salary, i.e $l_1 + l_2 + \dots + l_n \le s$.

Note that you don't have to spend all your $s$ dollars on salaries.

You have to answer $t$ test cases.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases.

The first line of each query contains two integers $n$ and $s$ ($1 \le n < 2 \cdot 10^5$, $1 \le s \le 2 \cdot 10^{14}$) — the number of employees and the amount of money you have. The value $n$ is not divisible by $2$.

The following $n$ lines of each query contain the information about employees. The $i$-th line contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 10^9$).

It is guaranteed that the sum of all $n$ over all queries does not exceed $2 \cdot 10^5$.

It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. $\sum\limits_{i=1}^{n} l_i \le s$.


-----Output-----

For each test case print one integer — the maximum median salary that you can obtain.


-----Example-----
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7

Output
11
1337
6



-----Note-----

In the first test case, you can distribute salaries as follows: $sal_1 = 12, sal_2 = 2, sal_3 = 11$ ($sal_i$ is the salary of the $i$-th employee). Then the median salary is $11$.

In the second test case, you have to pay $1337$ dollars to the only employee.

In the third test case, you can distribute salaries as follows: $sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7$. Then the median salary is $6$.

Source: codeforces | Difficulty: HARD
Tags: Sorting

Greedy algorithms


Solutions:
import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def bo(i):
	return ord(i) - ord('a')
from copy import *
from bisect import *
from itertools import permutations
t = fi()

def can(mid, s):
	p = s
	low = high = 0
	k = []
	for i in range(n):
		if d[i][1] < mid:
			p -= d[i][0]
			low += 1
		elif d[i][0] > mid:
			high += 1
			p -= d[i][0]
		else:
			p -= mid
			k.append(d[i])
	if low > (n - 1) // 2:
		return False
	if p >= 0:
		return True
	for i in range(low, (n - 1) // 2):
		if i - low >= len(k):
			break
		p += mid - k[i - low][0]
	return p >= 0
while t > 0:
	t -= 1
	(n, s) = mi()
	d = []
	for i in range(n):
		p = li()
		d.append(p)
	d.sort()
	l = 0
	r = 10 ** 10
	ans = d[n // 2][0]
	while l <= r:
		mid = l + (r - l) // 2
		if can(mid, s):
			ans = mid
			l = mid + 1
		else:
			r = mid - 1
	print(ans)


import sys

def highest_median(ranges, s):
	n = len(ranges)
	ranges = sorted(ranges)
	low = ranges[n // 2][0]
	high = sorted(ranges, key=lambda x: x[1])[n // 2][1] + 1
	while low + 1 < high:
		med = low + (high - low) // 2
		smaller = 0
		larger = 0
		total = 0
		for (l, h) in ranges:
			if l > med:
				smaller += 1
				total += l
			elif h < med:
				larger += 1
				total += l
		if smaller > n // 2:
			low = med
			continue
		if larger > n // 2:
			high = med
			continue
		for (l, h) in ranges:
			if larger == n // 2:
				break
			if l <= med <= h:
				larger += 1
				total += l
		total += med * (n - larger - smaller)
		if total > s:
			high = med
		else:
			low = med
	return low
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
t = int(input().strip())
for i in range(t):
	line = input().strip()
	vs = [int(v) for v in line.split(' ')]
	(n, s) = (vs[0], vs[1])
	ranges = []
	for j in range(n):
		line = input().strip()
		vs = [int(v) for v in line.split(' ')]
		ranges.append(vs)
	print(highest_median(ranges, s))


3
import array
import math
import os
import sys

def main():
	T = read_int()
	for _ in range(T):
		(N, S) = read_ints()
		A = [read_ints() for _ in range(N)]
		print(solve(N, S, A))

def solve(N, S, A):
	minv = [l for (l, r) in A]
	minv.sort()
	half = N // 2

	def feasible(target):
		low = []
		high = []
		mid = []
		for p in A:
			(l, r) = p
			if target < l:
				high.append(p)
			elif r < target:
				low.append(p)
			else:
				mid.append(p)
		if len(low) >= half + 1 or len(high) >= half + 1:
			return False
		tsum = 0
		for (l, r) in low:
			tsum += l
		for (l, r) in high:
			tsum += l
		mid.sort()
		midi = half - len(low)
		for i in range(midi):
			(l, r) = mid[i]
			tsum += l
		tsum += target * (len(mid) - midi)
		return tsum <= S
	lb = minv[half]
	ub = 10 ** 9 + 1
	while ub - lb > 1:
		mid = (ub + lb) // 2
		if feasible(mid):
			lb = mid
		else:
			ub = mid
	return lb
DEBUG = 'DEBUG' in os.environ

def inp():
	return sys.stdin.readline().rstrip()

def read_int():
	return int(inp())

def read_ints():
	return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
	if DEBUG:
		print(*value, sep=sep, end=end)

def __starting_point():
	main()
__starting_point()


import sys
input1 = sys.stdin.readline

def solve():
	(n, s) = [int(i) for i in input1().split()]
	empl = [[] for i in range(n)]
	for i in range(n):
		empl[i] = [int(j) for j in input1().split()]
	empl.sort(reverse=True)
	lg = 0
	rg = 10 ** 9 + 1
	while rg - lg > 1:
		mg = (rg + lg) // 2
		need = (n + 1) // 2
		money = s
		for [li, ri] in empl:
			if ri >= mg and need > 0:
				money -= max(mg, li)
				need -= 1
			else:
				money -= li
		if need == 0 and money >= 0:
			check = True
		else:
			check = False
		if check:
			lg = mg
		else:
			rg = mg
	print(lg)
t = int(input1())
while t > 0:
	empl = []
	solve()
	t -= 1


def check(x, s, a, n):
	num = (n + 1) // 2
	cur = 0
	sum_ = 0
	for i in range(n - 1, -1, -1):
		(l, r) = a[i]
		if cur == num:
			break
		if l >= x:
			cur += 1
		elif l <= x and x <= r:
			cur += 1
			sum_ += x - l
	if cur == num and sum_ <= s:
		return True
	return False
q = int(input())
ans = []
for _ in range(q):
	(n, s) = list(map(int, input().split()))
	a = [list(map(int, input().split())) for _ in range(n)]
	a = sorted(a, key=lambda x: x[0])
	s = s - sum([l for (l, r) in a])
	(l, u) = (a[n // 2][0], 1000000000)
	while u - l > 1:
		md = (u + l) // 2
		if check(md, s, a, n) == True:
			l = md
		else:
			u = md
	ans.append(str(l))
print('\n'.join([x for x in ans]))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, s) = list(map(int, input().split()))
	human = []
	x = n // 2 + 1
	for _ in range(n):
		human.append(list(map(int, input().split())))
	human.sort(reverse=True)
	remain = s
	for i in range(n):
		remain -= human[i][0]
	right = 10 ** 9 + 1
	left = 0
	while right - left > 1:
		mid = left + (right - left) // 2
		count = 0
		money = remain
		for i in range(n):
			if human[i][1] < mid:
				continue
			elif human[i][0] >= mid:
				count += 1
				continue
			elif money >= mid - human[i][0]:
				money -= mid - human[i][0]
				count += 1
			else:
				break
		if count >= x:
			left = mid
		else:
			right = mid
	print(left)


import sys
input = sys.stdin.buffer.readline

def check(num):
	count1 = 0
	count2 = 0
	spent = 0
	left = []
	for i in l:
		if i[0] > num:
			count2 += 1
			spent += i[0]
		elif i[1] < num:
			count1 += 1
			spent += i[0]
		else:
			left.append(i)
	if count2 > n // 2 + 1:
		return True
	elif count1 > n // 2:
		return False
	else:
		for i in left:
			if count2 != n // 2 + 1:
				spent += num
				count2 += 1
			else:
				spent += i[0]
				count1 += 1
		if count2 == n // 2 + 1 and count1 == n // 2 and (spent <= s):
			return True
		return False
for nt in range(int(input())):
	(n, s) = map(int, input().split())
	l = []
	for i in range(n):
		(a, b) = map(int, input().split())
		l.append((a, b))
	l.sort(reverse=True)
	if n == 1:
		print(min(l[0][1], s))
		continue
	low = 0
	high = 10 ** 10
	while low < high:
		mid = (low + high) // 2
		if check(mid):
			low = mid + 1
		else:
			high = mid - 1
	if check(low):
		print(low)
	else:
		print(low - 1)


import sys
input = sys.stdin.readline
t = int(input())
for test in range(t):
	(n, s) = map(int, input().split())
	LR = [tuple(map(int, input().split())) for i in range(n)]
	LR.sort(reverse=True)
	R = [r for (l, r) in LR]
	R.sort()
	MIN = LR[n // 2][0]
	MAX = R[n // 2]
	OK = (n + 1) // 2
	while MIN != MAX:
		mid = (MIN + MAX + 1) // 2
		count = 0
		money = 0
		for (l, r) in LR:
			if count < OK:
				if r >= mid:
					money += max(l, mid)
					count += 1
				else:
					money += l
			else:
				money += l
		if count >= OK and money <= s:
			MIN = mid
		else:
			MAX = mid - 1
	print(MIN)


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	(N, S) = map(int, input().split())
	LR = [list(map(int, input().split())) for _ in range(N)]
	Query.append((N, S, LR))
for (N, S, LR) in Query:
	G = []
	for (L, _) in LR:
		G.append(L)
	G.sort()
	l = G[N // 2]
	r = S + 1
	while r - l > 1:
		m = (l + r) // 2
		A = []
		B = []
		C = []
		for (L, R) in LR:
			if L <= m <= R:
				C.append(L)
			elif R < m:
				A.append(L)
			else:
				B.append(L)
		C.sort()
		if len(A) < N // 2 + 1 <= len(A) + len(C):
			if sum(A) + sum(B) + sum(C[:N // 2 - len(A)]) + m * (len(A) + len(C) - N // 2) <= S:
				l = m
			else:
				r = m
		else:
			r = m
	print(l)


import sys
input = sys.stdin.readline

def solve(mid):
	ans = 0
	cnt = 0
	tmp = []
	for i in range(n):
		(l, r) = info[i]
		if r < mid:
			ans += l
		elif mid < l:
			ans += l
			cnt += 1
		else:
			tmp.append(l)
	tmp.sort(reverse=True)
	nokori = (n + 1) // 2 - cnt
	for i in tmp:
		if nokori > 0:
			ans += mid
			nokori -= 1
		else:
			ans += i
	if ans <= s and nokori <= 0:
		return True
	else:
		return False
q = int(input())
ans = [0] * q
for qi in range(q):
	(n, s) = map(int, input().split())
	info = [list(map(int, input().split())) for i in range(n)]
	ok = 0
	ng = s + 1
	while abs(ok - ng) > 1:
		mid = (ok + ng) // 2
		if solve(mid):
			ok = mid
		else:
			ng = mid
	ans[qi] = ok
print('\n'.join(map(str, ans)))


import sys
input = lambda : sys.stdin.readline().rstrip()
T = int(input())
for _ in range(T):
	(N, S) = list(map(int, input().split()))
	X = []
	for __ in range(N):
		(l, r) = list(map(int, input().split()))
		X.append((l, r))
	ok = 1
	ng = 10 ** 9 + 1
	while ng - ok > 1:
		m = (ok + ng) // 2
		A = []
		B = []
		for i in range(N):
			if X[i][1] >= m:
				A.append(X[i][0])
			else:
				B.append(X[i][0])
		A = sorted(A)[::-1]
		if len(A) > N // 2 and sum([max(a, m) for a in A[:N // 2 + 1]]) + sum(A[N // 2 + 1:]) + sum(B) <= S:
			ok = m
		else:
			ng = m
	print(ok)


import os
import sys
from io import BytesIO, IOBase

def main():
	for t in range(int(input())):
		(n, m) = [int(j) for j in input().split()]
		ls = []
		r_max = 0
		for i in range(n):
			(l, r) = [int(j) for j in input().split()]
			m -= l
			r_max = max(r_max, r)
			ls.append((l, r))
		ls.sort()
		meind = (n - 1) // 2
		lf = ls[(n - 1) // 2][0]
		rt = r_max
		ans = ls[(n - 1) // 2][0]

		def fun(med):
			mon = m
			cnt = 0
			for i in range(meind, n):
				if ls[i][0] < med:
					if ls[i][1] >= med:
						mon -= med - ls[i][0]
					else:
						cnt += 1
			if cnt > 0:
				for i in range(meind - 1, -1, -1):
					if cnt <= 0:
						break
					if ls[i][1] >= med:
						mon -= med - ls[i][0]
						cnt -= 1
			if mon >= 0 and cnt <= 0:
				return True
			return False
		while lf <= rt:
			mid = lf + (rt - lf) // 2
			if fun(mid) == True:
				ans = max(ans, mid)
				lf = mid + 1
			else:
				rt = mid - 1
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline

def judge(x):
	salary = 0
	(left_cnt, right_cnt) = (0, 0)
	arr = []
	for (li, ri) in lr:
		if ri < x:
			salary += li
			left_cnt += 1
		elif x < li:
			salary += li
			right_cnt += 1
		else:
			arr.append(li)
	arr.sort()
	salary += sum(arr[:(n - 1) // 2 - left_cnt]) + (1 + (n - 1) // 2 - right_cnt) * x
	return salary <= s

def binary_search(l, r):
	while l <= r:
		mid = (l + r) // 2
		if judge(mid):
			l = mid + 1
		else:
			r = mid - 1
	return r
t = int(input())
for _ in range(t):
	(n, s) = map(int, input().split())
	lr = [tuple(map(int, input().split())) for _ in range(n)]
	l = [li for (li, _) in lr]
	r = [ri for (_, ri) in lr]
	l.sort()
	r.sort()
	print(binary_search(l[n // 2], r[n // 2]))


from sys import stdin
input = stdin.readline
q = int(input())
for rwre in range(q):
	(n, s) = map(int, input().split())
	przed = [list(map(int, input().split())) for i in range(n)]
	przed.sort()
	przed.reverse()
	l = 1
	p = 10 ** 9
	while abs(p - l) > 0:
		mozna = 1
		sr = (p + l + 1) // 2
		duze = [przed[i] for i in range(n) if przed[i][1] >= sr]
		male = [przed[i] for i in range(n) if przed[i][1] < sr]
		if len(duze) <= n // 2:
			mozna = 0
		else:
			spent = 0
			dudes = 0
			for i in range(n // 2 + 1):
				spent += max(sr, duze[i][0])
			dudes = n // 2 + 1
			duze = duze[n // 2 + 1:]
			for du in duze:
				spent += du[0]
			for ma in male:
				spent += ma[0]
			if spent > s:
				mozna = 0
		if mozna == 1:
			l = sr
		else:
			p = sr - 1
	print((p + l) // 2)


import sys
import math
from collections import defaultdict
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))

def write(*args, sep='\n'):
	for i in args:
		sys.stdout.write('{}'.format(i) + sep)
INF = float('inf')
MOD = int(1000000000.0 + 7)
for t in range(int(input())):
	(n, x) = read()
	lr = sorted([list(read()) for i in range(n)], reverse=True)
	s = 0
	e = 1 << 32
	while s <= e:
		m = (s + e) // 2
		money = 0
		(a, b, c) = ([], [], [])
		for (l, r) in lr:
			if l > m:
				c.append((l, r))
				money += l
			elif r < m:
				a.append((l, r))
				money += l
			else:
				b.append((l, r))
		if money > x or len(a) >= n // 2 + 1:
			e = m - 1
			continue
		need = n // 2 + 1 - len(c)
		cnt = 0
		for (l, r) in b:
			if cnt < need:
				money += m
				cnt += 1
			else:
				money += l
		if money <= x:
			s = m + 1
		else:
			e = m - 1
	print(e)


from sys import stdin, stdout

def fun1(n, m, l, s):
	cl = 0
	cr = 0
	cm = 0
	for i in range(n):
		if l[i][1] < m:
			s -= l[i][0]
			cl += 1
		elif l[i][0] > m:
			s -= l[i][0]
			cr += 1
		else:
			cm += 1
			if cm + cr <= 1 + n // 2:
				s -= m
			else:
				s -= l[i][0]
		if s < 0 or cr > n // 2 or cl > n // 2:
			return 0
	return 1

def search(n, low, high, l, su):
	l1 = l[::-1]
	while low < high:
		mid = (low + high) // 2
		if fun1(n, mid, l1, su):
			low = mid + 1
		else:
			high = mid
	if fun1(n, low, l1, su):
		return low
	return low - 1

def main():
	for _ in range(int(stdin.readline())):
		(n, su) = [int(x) for x in stdin.readline().split()]
		l = [[-1, -1] for i in range(n)]
		l2 = [-1 for i in range(n)]
		for i in range(n):
			inp = [int(j) for j in stdin.readline().split()]
			l[i] = inp
			l2[i] = inp[0]
		l.sort()
		low = int(l[n // 2][0])
		print(search(n, low, 10 ** 9 + 1, l, su))
main()


from sys import stdin
from operator import itemgetter, attrgetter

def check(salary, mid, s):
	cnt = 0
	for i in range(len(salary)):
		if salary[i][0] > mid:
			s -= salary[i][0]
			cnt += 1
		elif salary[i][0] <= mid and salary[i][1] >= mid:
			if cnt < (len(salary) + 1) // 2:
				s -= mid
				cnt += 1
			else:
				s -= salary[i][0]
		elif salary[i][1] < mid:
			s -= salary[i][0]
	if cnt >= (len(salary) + 1) // 2 and s >= 0:
		return True
	else:
		return False
t = int(stdin.buffer.readline())
for _ in range(t):
	salary = list()
	(n, s) = map(int, stdin.buffer.readline().split())
	(ansL, ansR) = (4557430888798830399, -1)
	for i in range(n):
		(l, r) = map(int, stdin.buffer.readline().split())
		ansL = min(ansL, l)
		ansR = max(ansR, r)
		salary.append((l, r))
	salary = sorted(salary, key=itemgetter(0), reverse=True)
	l = ansL
	r = ansR
	ans = None
	while l <= r:
		mid = (l + r) // 2
		if check(salary, mid, s):
			ans = mid
			l = mid + 1
		else:
			r = mid - 1
	print(ans)


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

def bisearch_max(mn, mx, func):
	ok = mn
	ng = mx
	while ok + 1 < ng:
		mid = (ok + ng) // 2
		if func(mid):
			ok = mid
		else:
			ng = mid
	return ok

def check(m):
	(A1, A2, A3) = ([], [], [])
	cnt = k = 0
	for (l, r) in LR:
		if r < m:
			k += l
		elif m <= l:
			cnt += 1
			k += l
		else:
			A3.append((l, r))
			k += l
	if k > K:
		return False
	if cnt + len(A3) < midcnt:
		return False
	if cnt >= midcnt and k <= K:
		return True
	A3.sort(reverse=True)
	for (l, r) in A3:
		cnt += 1
		k += m - l
		if k > K:
			return False
		if cnt >= midcnt and k <= K:
			return True
	return False
for _ in range(INT()):
	(N, K) = MAP()
	midcnt = N // 2 + 1
	LR = []
	for i in range(N):
		(l, r) = MAP()
		LR.append((l, r))
	res = bisearch_max(0, 10 ** 9 + 1, check)
	print(res)


import os, sys, atexit
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
_OUTPUT_BUFFER = StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
t = int(input())
while t:
	t += -1
	(n, s) = map(int, input().split())
	l = []
	for i in range(n):
		temp = list(map(int, input().split()))
		l.append(temp)
	l.sort()
	low = 0
	high = 10 ** 9 + 10
	while 1:
		ch = 1
		mid = (low + high) // 2
		cnt = 0
		total = 0
		re = 0
		for i in range(n):
			if l[i][1] < mid or mid <= l[i][0]:
				total += l[i][0]
			if mid <= l[i][0]:
				cnt -= -1
			if l[i][0] < mid <= l[i][1]:
				re -= -1
		if re < max(0, (n + 1) // 2 - cnt):
			high = mid - 1
			if high < low:
				break
		else:
			tt = max(0, (n + 1) // 2 - cnt)
			total += tt * mid
			ddd = 0
			for i in range(n):
				if ddd == re - tt:
					break
				if l[i][0] < mid <= l[i][1]:
					ddd -= -1
					total += l[i][0]
			if total > s:
				high = mid - 1
				if high < low:
					break
			else:
				low = mid + 1
				if high < low:
					break
	print(high)


def main():
	from array import array
	import sys
	input1 = sys.stdin.readline
	for _ in range(int(input1())):
		(n, s) = map(int, input1().split())
		n1 = (n + 1) // 2
		z = array('i', (0,))
		ls = z * n
		rs = z * n
		for i in range(n):
			(ls[i], rs[i]) = map(int, input1().split())
		for l_ in ls:
			s -= l_
		(lbs, rbs) = (1, 1000000001)
		while lbs + 1 < rbs:
			m = (lbs + rbs) // 2
			st = sorted((min(l_, m) for (l_, r) in zip(ls, rs) if r >= m), reverse=True)
			if len(st) >= n1 and m * n1 <= s + sum(st[:n1]):
				lbs = m
			else:
				rbs = m
		sys.stdout.write(f'{lbs}\n')
main()


import bisect
import os, sys, atexit
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
_OUTPUT_BUFFER = StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

def solve():
	t = int(input())
	for _ in range(t):
		(n, s) = map(int, input().split())
		ranges = []
		for _ in range(n):
			(l, r) = map(int, input().split())
			ranges.append([r, l])
		ranges.sort()
		sumli = [0]
		(li, ri) = ([], [])
		for (r, l) in ranges:
			sumli.append(sumli[-1] + l)
			li.append(l)
			ri.append(r)
		(left, right) = (0, ri[n // 2])
		while left != right:
			mid = (left + right + 1) // 2
			total = 0
			riIndex = bisect.bisect_left(ri, mid)
			if n - riIndex > n // 2:
				total += sumli[riIndex]
				sortedLi = sorted(li[riIndex:])
				liIndex = bisect.bisect_left(sortedLi, mid)
				total += sum(sortedLi[liIndex:])
				countN2 = max((n + 1) // 2 - (len(sortedLi) - liIndex), 0)
				total += countN2 * mid + sum(sortedLi[:liIndex - countN2])
				if total > s:
					right = mid - 1
				elif countN2 == 0:
					left = sortedLi[-(n // 2 + 1)]
				else:
					left = mid
			else:
				right = mid - 1
		print((left + right) // 2)
try:
	solve()
except Exception as e:
	print(e)


import itertools
import bisect
from collections import OrderedDict
from sys import stdin, stdout

class Solution:

	def __init__(self, n, s, salary_limits):
		self.n = n
		self.half_n = (n - 1) // 2
		self.s = s
		self.salary_limits = salary_limits
		self.l_sorted = sorted(salary_limits, key=lambda limits: limits[0])
		self.r_sorted = sorted(salary_limits, key=lambda limits: limits[1])

		def cummulative_sum_func(tup1, tup2):
			return (tup1[0] + tup2[0],)
		self.l_sorted_sums = [x[0] for x in list(itertools.accumulate(self.l_sorted[::-1], func=cummulative_sum_func))][::-1]
		self.r_sorted_sums = [x[0] for x in list(itertools.accumulate(self.r_sorted, func=cummulative_sum_func))]
		self.r_sorted_complementary_sums = self._compute_r_complementary_sums()
		self.l_sorted_l_projection = list(map(lambda tup: tup[0], self.l_sorted))
		self.r_sorted_r_projection = list(map(lambda tup: tup[1], self.r_sorted))

	def _compute_r_complementary_sums(self):
		lo_set = OrderedDict.fromkeys(self.l_sorted[:self.half_n])
		for tup in self.l_sorted[:self.half_n]:
			lo_set[tup] = 1 + lo_set[tup] if lo_set[tup] is not None else 1
		acc = sum((tup[0] for tup in self.l_sorted[:self.half_n]))
		result = [acc]
		for sal_limit in self.r_sorted[:self.half_n]:
			if sal_limit in lo_set:
				lo_set[sal_limit] -= 1
				if lo_set[sal_limit] <= 0:
					lo_set.pop(sal_limit)
				acc -= sal_limit[0]
			else:
				(k, v) = lo_set.popitem()
				if v - 1 > 0:
					lo_set[k] = v - 1
				acc -= k[0]
			result.append(acc)
		return result

	def _is_possible(self, median_sal):
		disjoint_sal_limits_overstepping_median = bisect.bisect_right(self.l_sorted_l_projection, median_sal)
		disjoint_sal_limits_understepping_median = bisect.bisect_left(self.r_sorted_r_projection, median_sal)
		cost = (self.l_sorted_sums[disjoint_sal_limits_overstepping_median] if disjoint_sal_limits_overstepping_median < self.n else 0) + (self.r_sorted_sums[disjoint_sal_limits_understepping_median - 1] if disjoint_sal_limits_understepping_median > 0 else 0) + median_sal * (disjoint_sal_limits_overstepping_median - self.half_n) + self.r_sorted_complementary_sums[disjoint_sal_limits_understepping_median]
		return cost <= self.s

	def solve(self):
		ans = self.l_sorted[self.half_n][0]
		lo = self.l_sorted[self.half_n][0]
		hi = self.r_sorted[self.half_n][1]
		while lo <= hi:
			mid = (lo + hi) // 2
			if self._is_possible(median_sal=mid):
				ans = mid
				lo = mid + 1
			else:
				hi = mid - 1
		return ans

def main():
	t = int(stdin.readline())
	for i in range(t):
		(n, s) = map(int, stdin.readline().split())
		salary_limits = [tuple(map(int, stdin.readline().split())) for i in range(n)]
		if n == 1:
			stdout.write(str(min(s, salary_limits[0][1])))
		else:
			solution = Solution(n=n, s=s, salary_limits=salary_limits)
			stdout.write(str(solution.solve()))
		stdout.write('\n')
main()


import sys
from bisect import bisect_left
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
	(n, s) = map(int, input().split())
	mid = n >> 1
	rl = []
	for i in range(n):
		(li, ri) = map(int, input().split())
		rl.append((ri, li))
	rl.sort()
	leftSum = [0]
	currSum = 0
	for i in range(n >> 1):
		currSum += rl[i][1]
		leftSum.append(currSum)
	L = 1
	R = 10 ** 9 + 1
	while L + 1 < R:
		median = L + R >> 1
		st = bisect_left(rl, (median, 0))
		if st > mid:
			R = median
			continue
		cost = leftSum[st]
		ls = []
		for i in range(st, n):
			ls.append(rl[i][1])
		ls.sort()
		if ls[-mid - 1] > median:
			L = median
			continue
		for i in range(mid + 1):
			cost += max(median, ls[-i - 1])
		for i in range(mid + 1, n - st):
			cost += ls[-i - 1]
		if cost <= s:
			L = median
		else:
			R = median
	print(L)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	(n, k) = map(int, input().split())
	a = []
	for i in range(n):
		(l, r) = map(int, input().split())
		a.append((l, r))

	def check(mid):
		less = 0
		more = 0
		x = 0
		e = []
		er = 0
		er1 = 0
		for i in range(n):
			if a[i][1] < mid:
				less += 1
				er += a[i][0]
			elif a[i][0] > mid:
				more += 1
				er1 += a[i][0]
			else:
				x += 1
				e.append(a[i][0])
		x -= 1
		e.sort()
		if more > n // 2:
			return 1
		elif less > n // 2:
			return -1
		tot = er + er1 + sum(e[:n // 2 - less]) + (x - n // 2 + less + 1) * mid
		if tot <= k:
			return 0
		return -1
	st = 0
	end = k
	ans = 0
	while st <= end:
		mid = (st + end) // 2
		ch = check(mid)
		if ch == 0:
			ans = mid
			st = mid + 1
		elif ch == 1:
			st = mid + 1
		else:
			end = mid - 1
	print(ans)


def main():

	def getLowestPossibleMedian(lr, n):
		lr.sort(key=lambda x: x[0])
		return lr[n // 2][0]

	def checkPossibleMedian(lr, guess, n, s):
		potentialUpper = []
		lower = []
		lowerCnts = n // 2
		upperCnts = n - lowerCnts
		for (l, r) in lr:
			if r >= guess:
				potentialUpper.append([l, r])
			else:
				lower.append([l, r])
		if len(potentialUpper) < upperCnts:
			return False
		potentialUpper.sort(key=lambda x: x[0], reverse=True)
		for i in range(upperCnts, len(potentialUpper)):
			lower.append(potentialUpper[i])
		assert len(lower) == lowerCnts
		requiredSalary = 0
		for (l, r) in lower:
			requiredSalary += l
		for i in range(upperCnts):
			requiredSalary += max(guess, potentialUpper[i][0])
		return requiredSalary <= s
	t = int(input())
	allans = []
	for _ in range(t):
		(n, s) = readIntArr()
		lr = []
		for __ in range(n):
			lr.append(readIntArr())
		m = getLowestPossibleMedian(lr, n)
		ans = m
		b = s
		while b > 0:
			while checkPossibleMedian(lr, ans + b, n, s):
				ans += b
			b //= 2
		allans.append(ans)
	multiLineArrayPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultVal, dimensionArr):
	dv = defaultVal
	da = dimensionArr
	if len(da) == 1:
		return [dv for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 998244353
for _abc in range(1):
	main()


def main():
	import sys
	import heapq
	input = sys.stdin.readline
	t = int(input())
	for _ in range(t):
		(N, S) = map(int, input().split())
		cost = []
		m = []
		for _ in range(N):
			(l, r) = map(int, input().split())
			cost.append((l, r))
			m.append(l)
		m.sort()
		ok = m[N // 2]
		ng = S + 1
		mid = (ok + ng) // 2
		while ng - ok > 1:
			big = []
			small = []
			for (l, r) in cost:
				if r >= mid:
					big.append(-l)
				else:
					small.append(l)
			if len(big) < N // 2 + 1:
				ng = mid
				mid = (ok + ng) // 2
				continue
			heapq.heapify(big)
			C = 0
			for i in range(N // 2 + 1):
				C += max(-heapq.heappop(big), mid)
			for l in big:
				small.append(-l)
			C += sum(small)
			if C <= S:
				ok = mid
			else:
				ng = mid
			mid = (ok + ng) // 2
		print(ok)
main()


import sys
readline = sys.stdin.readline
inf = 10 ** 16

def calc(m, L, R):
	N = len(L)
	cl = 0
	cr = 0
	ss = 0
	candi = []
	for i in range(N):
		if L[i] > m:
			cr += 1
			ss += L[i]
		elif R[i] < m:
			cl += 1
			ss += L[i]
		else:
			candi.append(L[i])
	cm = len(candi)
	if cl > N // 2:
		return inf
	k = min(cm, N // 2 - cl)
	candi.sort()
	ss += sum(candi[:k])
	ss += (cm - k) * m
	return ss
T = int(readline())
Ans = [None] * T
for qu in range(T):
	(M, LS) = map(int, readline().split())
	L = [None] * M
	R = [None] * M
	for i in range(M):
		(L[i], R[i]) = map(int, readline().split())
	ok = 0
	ng = 10 ** 9 + 1
	while abs(ok - ng) > 1:
		med = (ok + ng) // 2
		if calc(med, L, R) <= LS:
			ok = med
		else:
			ng = med
	Ans[qu] = ok
print('\n'.join(map(str, Ans)))


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(200001)]
pp = [0] * 200001

def SieveOfEratosthenes(n=200000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
for i in range(1, 200001):
	pp[i] = pp[i - 1]
	if prime[i]:
		pp[i] += 1
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = []
	for i in range(n):
		(l, r) = map(int, input().split())
		a.append((l, r))

	def check(mid):
		less = 0
		more = 0
		x = 0
		e = []
		er = 0
		er1 = 0
		for i in range(n):
			if a[i][1] < mid:
				less += 1
				er += a[i][0]
			elif a[i][0] > mid:
				more += 1
				er1 += a[i][0]
			else:
				x += 1
				e.append(a[i][0])
		x -= 1
		e.sort()
		if more > n // 2:
			return 1
		elif less > n // 2:
			return -1
		tot = er + er1 + sum(e[:n // 2 - less]) + (x - n // 2 + less + 1) * mid
		if tot <= k:
			return 0
		return -1
	st = 0
	end = k
	ans = 0
	while st <= end:
		mid = (st + end) // 2
		ch = check(mid)
		if ch == 0:
			ans = mid
			st = mid + 1
		elif ch == 1:
			st = mid + 1
		else:
			end = mid - 1
	print(ans)


def check(mid):
	x = []
	y = []
	z = []
	for i in it:
		if i[1] < mid:
			x.append(i)
		elif i[0] >= mid:
			y.append(i)
		else:
			z.append(i)
	co = sum([i[0] for i in x])
	co += sum([i[0] for i in y])
	ll = len(y)
	m = 0
	ne = max(0, (n + 1) // 2 - ll)
	if ne > len(z):
		return False
	j = 0
	for i in z:
		if j < len(z) - ne:
			co += i[0]
		else:
			co += mid
		j += 1
	return co <= s
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, s) = list(map(int, input().split()))
	it = []
	for i in range(n):
		it.append(list(map(int, input().split())))
	it.sort()
	l = 1
	r = max(it, key=lambda x: x[1])[1] + 1
	while abs(l - r) >= 2:
		mid = (l + r) // 2
		st = check(mid)
		if st:
			l = mid
		else:
			r = mid
	ma = l
	for i in range(l, r + 1):
		st = check(i)
		if st:
			ma = max(ma, i)
	print(ma)


import sys
input = sys.stdin.readline
import heapq
sys.setrecursionlimit(100000)

def getN():
	return int(input())

def getList():
	return list(map(int, input().split()))

def solve():
	(ls, rs) = ([], [])
	(n, money) = getList()
	sals = []
	for _ in range(n):
		(a, b) = getList()
		sals.append((a, b))
	ans_mx = 10 ** 10
	ans_mn = 0
	while ans_mx - ans_mn > 1:
		tmp = 0
		heap = []
		mid = (ans_mn + ans_mx) // 2
		for sal in sals:
			if sal[1] < mid:
				tmp += sal[0]
			else:
				heapq.heappush(heap, (-sal[0], -sal[1]))
		if len(heap) < (n + 1) // 2:
			ans_mx = mid
			continue
		high = 0
		tgt = n // 2
		while heap:
			sal_cur = heapq.heappop(heap)
			if high <= tgt:
				tmp += max(mid, -sal_cur[0])
				high += 1
			else:
				tmp += -sal_cur[0]
		if tmp <= money:
			ans_mn = mid
		else:
			ans_mx = mid
	tmp = 0
	heap = []
	mid = ans_mx
	for sal in sals:
		if sal[1] < mid:
			tmp += sal[0]
		else:
			heapq.heappush(heap, (-sal[0], -sal[1]))
	if len(heap) < (n + 1) // 2:
		print(ans_mn)
		return
	high = 0
	tgt = n // 2
	while heap:
		sal_cur = heapq.heappop(heap)
		if high <= tgt:
			tmp += max(mid, -sal_cur[0])
			high += 1
		else:
			tmp += -sal_cur[0]
	if tmp <= money:
		print(mid)
		return
	else:
		print(ans_mn)
		return

def main():
	t = getN()
	for times in range(t):
		solve()

def __starting_point():
	main()
__starting_point()


a = int(input())
ans = []
import sys
input = sys.stdin.readline

def checker(ans, mid, n, s):
	g1 = n // 2
	c1 = 0
	c2 = 0
	c3 = 0
	cost = 0
	t1 = []
	for i in range(len(ans)):
		if ans[i][0] <= mid <= ans[i][1]:
			t1.append([ans[i][0], ans[i][1]])
		elif ans[i][1] < mid:
			c3 += 1
			cost += ans[i][0]
		else:
			c1 += 1
			cost += ans[i][0]
	if c1 > g1 or c3 > g1:
		if c3 > g1:
			return 0
		else:
			return 2
	else:
		left = g1 - c3
		leftr = g1 - c1
		for i in range(left):
			cost += t1[i][0]
		cost += (leftr + 1) * mid
		if cost <= s:
			return 1
		else:
			return 0
import math
for i in range(a):
	(n, s) = map(int, input().split())
	ans = []
	mini = math.inf
	maxa = 0
	for i in range(n):
		(x, y) = map(int, input().split())
		ans.append([x, y])
		mini = min(x, y, mini)
		maxa = max(x, y, maxa)
	ans.sort()
	maxa += 5
	value = 0
	while mini < maxa:
		mid = (mini + maxa) // 2
		t = checker(ans, mid, n, s)
		if t == 0:
			maxa = mid
		else:
			if t == 1:
				value = max(value, mid)
			mini = mid + 1
	print(value)


import sys
readline = sys.stdin.readline
rdw = lambda : readline().split()
rdwl = lambda : list(readline().split())
rdi = lambda : int(readline())
rdis = lambda : map(int, readline().split())
rdisl = lambda : list(map(int, readline().split()))
rdrows = lambda cnt: [tuple(rdis()) for _ in range(cnt)]

def solve():
	(n, s) = rdis()
	cm = n + 1 >> 1
	a = rdrows(n)
	a.sort()
	(l, r) = (a[n >> 1][0], 10 ** 9 + 1)
	res = l
	while l <= r:
		m = l + r >> 1
		need = 0
		cnt = 0
		for i in range(n - 1, -1, -1):
			(li, ri) = a[i]
			if li >= m:
				need += li
				cnt += 1
			elif cnt < cm and ri >= m:
				need += m
				cnt += 1
			else:
				need += li
		if cnt >= cm and need <= s:
			res = m
			l = m + 1
		else:
			r = m - 1
	print(res)
tests = 1
tests = rdi()
for testnum in range(tests):
	solve()


from sys import stdin
from sys import setrecursionlimit as SRL
SRL(10 ** 7)
rd = stdin.readline
rrd = lambda : map(int, rd().strip().split())
q = int(input())
lr = []

def check(x, s):
	cnt = 0
	tt = []
	xcnt = 0
	for (l, r) in lr[::-1]:
		if l > x:
			tt.append(l)
			cnt += 1
		elif r >= x and l <= x and (cnt < n // 2 + 1):
			cnt += 1
			xcnt += 1
		else:
			tt.append(l)
	if cnt == n // 2 + 1 and x * xcnt + sum(tt) <= s:
		return True
	return False
while q:
	(n, s) = rrd()
	lr = []
	for i in range(n):
		(l, r) = rrd()
		lr.append([l, r])
	lr.sort()
	l = lr[n // 2][0]
	r = s + 1
	while l < r:
		m = (l + r) // 2
		if check(m, s):
			l = m + 1
		else:
			r = m
	print(r - 1)
	q -= 1


import sys

def I():
	return sys.stdin.readline().rstrip()
for _ in range(int(I())):
	(n, s) = map(int, I().split())
	half = n // 2
	lows = 0
	(l, r) = ([], [])
	for _ in range(n):
		(x, y) = map(int, I().split())
		lows += x
		l.append(x)
		r.append(y)
	money = 0
	t = 1
	while t <= 1000000000.0:
		t *= 2
	t //= 2
	while t > 0:
		people = 0
		new_money = money + t
		left = []
		for (low, high) in zip(l, r):
			if low <= new_money <= high:
				left.append(new_money - low)
			elif new_money < low:
				people += 1
		left.sort()
		people = half + 1 - people
		if people <= 0 or (len(left) >= people and lows + sum(left[:people]) <= s):
			money += t
		t //= 2
	print(money)


import sys
import operator
input = sys.stdin.buffer.readline

def f(med):
	total = 0
	cnt = 0
	for x in salaries:
		if x[1] < med:
			total += x[0]
		elif cnt < n / 2:
			total += max(x[0], med)
			cnt += 1
		else:
			total += x[0]
	if total > s or cnt < n / 2:
		return False
	return True
q = int(input())
for _ in range(q):
	salaries = []
	minl = 999999999999999
	maxl = -1
	(n, s) = map(int, input().split())
	for __ in range(n):
		(l, r) = map(int, input().split())
		if l < minl:
			minl = l
		if r > maxl:
			maxl = r
		salaries.append((l, r))
	salaries.sort(reverse=True)
	a = minl
	b = maxl
	while b >= a:
		m = (a + b) // 2
		if f(m):
			a = m + 1
		else:
			b = m - 1
	print(b)


import sys
from collections import defaultdict

def check(l, x, lim):
	(low, high, n) = ([], [], len(l))
	for i in range(n):
		if l[i][1] < x:
			low.append(l[i][0])
		else:
			high.append(l[i][0])
	(a, b) = (len(low), len(high))
	if b <= n // 2:
		return False
	s = sum(low)
	i = 0
	for i in range(n // 2 - a):
		s += high[i]
	for j in range(max(n // 2 - a, 0), b):
		if high[j] <= x:
			s += x
		else:
			s += high[j]
	if s <= lim:
		return True
	return False
t = int(sys.stdin.readline())
for _ in range(t):
	(n, s) = map(int, sys.stdin.readline().split())
	l = [[-1, -1] for _ in range(n)]
	for i in range(n):
		(u, v) = map(int, sys.stdin.readline().split())
		l[i] = [u, v]
	l.sort()
	high = 100000000000000
	(low, ans) = (0, -1)
	while low <= high:
		mid = (low + high) // 2
		if check(l, mid, s):
			ans = max(ans, mid)
			low = mid + 1
		else:
			high = mid - 1
	print(ans)


def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, s) = readIntArr()
		lr = []
		for __ in range(n):
			lr.append(readIntArr())
		lr.sort(key=lambda x: x[0])
		guess = lr[n // 2][0]

		def isPossible(median):
			lowerCnt = n // 2
			upperCnt = n - lowerCnt
			lower = []
			upper = []
			unsure = []
			for (l, r) in lr:
				if r < median:
					lower.append([l, r])
				elif l >= median:
					upper.append([l, r])
				else:
					unsure.append([l, r])
			if len(lower) > lowerCnt:
				return False
			elif len(upper) > upperCnt:
				assert False
			unsure.sort(key=lambda x: x[0])
			for i in range(len(unsure)):
				if len(lower) < lowerCnt:
					lower.append(unsure[i])
				else:
					upper.append(unsure[i])
			minRequiredS = 0
			for (l, r) in lower:
				minRequiredS += l
			for (l, r) in upper:
				minRequiredS += max(l, median)
			return s >= minRequiredS
		b = s
		while b > 0:
			while isPossible(guess + b):
				guess += b
			b //= 2
		allans.append(guess)
	multiLineArrayPrint(allans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultVal, dimensionArr):
	dv = defaultVal
	da = dimensionArr
	if len(da) == 1:
		return [dv for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


import sys
input = sys.stdin.readline
t = int(input())

def ok(mid, l, n, s):
	su = 0
	cnt = 0
	ll = []
	for i in range(n):
		if l[i][1] < mid:
			su += l[i][0]
		elif l[i][0] >= mid:
			su += l[i][0]
			cnt += 1
		else:
			ll.append(l[i])
	ll.sort()
	ne = max(0, (n + 1) // 2 - cnt)
	if ne > len(ll):
		return False
	for i in range(len(ll)):
		if i < len(ll) - ne:
			su += ll[i][0]
		else:
			su += mid
	return su <= s
while t:
	l = []
	(n, s) = map(int, input().split())
	for i in range(n):
		(ll, r) = map(int, input().split())
		l.append((ll, r))
	l.sort()
	lf = 0
	r = 10 ** 9 + 100
	while r - lf > 1:
		mid = lf + (r - lf) // 2
		if ok(mid, l, n, s):
			lf = mid
		else:
			r = mid
	print(lf)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math as mt
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)
mod = int(1000000000.0) + 7

def power(k, n):
	if n == 0:
		return 1
	if n % 2:
		return power(k, n - 1) * k % mod
	t = power(k, n // 2)
	return t * t % mod

def totalPrimeFactors(n):
	count = 0
	if n % 2 == 0:
		count += 1
		while n % 2 == 0:
			n //= 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			count += 1
			while n % i == 0:
				n //= i
		i += 2
	if n > 2:
		count += 1
	return count

def main():
	for _ in range(int(input())):
		(n, s) = map(int, input().split())
		lr = []
		for i in range(n):
			lr.append(list(map(int, input().split())))
		lr.sort()
		l = 0
		r = 10 ** 9 + 1
		ans = 0
		nb2 = n >> 1
		while r - l > 1:
			mid = l + r >> 1
			low = 0
			high = 0
			common = []
			now = mid
			for i in lr:
				if i[1] < mid:
					low += 1
					now += i[0]
				elif i[0] > mid:
					high += 1
					now += i[0]
				elif i[0] <= mid <= i[1]:
					common.append(i)
			f = 1
			if low > nb2 or high > nb2:
				if low > nb2:
					f = 0
			else:
				for i in range(nb2 - low):
					now += common[i][0]
				now += (nb2 - high) * mid
				if now > s:
					f = 0
			if f:
				l = mid
				ans = max(ans, mid)
			else:
				r = mid
		print(ans)
	return
main()


import sys

def BinSearch():
	pass
t = int(sys.stdin.readline())
for _ in range(t):
	(n, s) = map(int, sys.stdin.readline().split())
	tmp = [tuple(map(int, sys.stdin.readline().split())) for _ in range(n)]
	mid = s
	r = s
	l = 0
	tmp.sort()
	while True:
		tp = []
		tp1 = 0
		tmpSum = 0
		for x in tmp:
			if x[0] >= mid:
				tp1 += 1
				tmpSum += x[0]
			elif x[1] >= mid:
				tp.append(x)
			else:
				tmpSum += x[0]
		q = len(tp)
		qq = (n + 1) // 2 - tp1
		for i in range(q):
			if i >= qq:
				tmpSum += tp[q - 1 - i][0]
		if qq > q or tmpSum + qq * mid > s:
			if r - l <= 1:
				print(r - 1)
				break
			r = mid
		else:
			if r - l <= 1:
				print(l)
				break
			l = mid
		mid = l + (r - l) // 2


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = float('inf')
mod = int(1000000000.0) + 7
for t in range(int(data())):
	(n, s) = mdata()
	lis = sorted([mdata() for i in range(n)])
	sum1 = 0
	m = 0
	for i in range(n):
		sum1 += lis[i][0]
		m = max(m, lis[i][1])
	s -= sum1
	(start, end) = (0, m)
	while start <= end:
		sum2 = s
		mid = (start + end) // 2
		cnt = 0
		for (i, j) in lis[::-1]:
			if i >= mid:
				cnt += 1
			elif j >= mid and sum2 >= mid - i:
				cnt += 1
				sum2 -= mid - i
		if cnt >= n // 2 + 1:
			start = mid + 1
		else:
			end = mid - 1
	out(end)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	(n, s) = map(int, input().split())
	L = [0] * n
	R = [0] * n
	RL = [0] * n
	for i in range(n):
		(l, r) = map(int, input().split())
		L[i] = l
		R[i] = r
		RL[i] = (r, l)
	L.sort()
	R.sort()

	def is_ok(x):
		t = 0
		cnt1 = 0
		cnt2 = 0
		g = []
		for i in range(n):
			(r, l) = RL[i]
			if r < x:
				t += l
			elif x <= l:
				cnt1 += 1
				t += l
			else:
				cnt2 += 1
				g.append(l)
		g.sort()
		need = (n + 1) // 2 - cnt1
		for i in range(len(g) - need):
			t += g[i]
		t += x * need
		if t <= s:
			return True
		else:
			return False
	ok = L[n // 2]
	ng = R[n // 2] + 1
	while ok + 1 < ng:
		c = (ok + ng) // 2
		if is_ok(c):
			ok = c
		else:
			ng = c
	print(ok)


from sys import stdin, stdout

def getmaximummediansalary(lra, n, s):
	l = 0
	h = s
	while l < h:
		m = (l + h + 1) // 2
		if candistribute(m, lra, s):
			l = m
		else:
			h = m - 1
	return l

def candistribute(m, lra, s):
	cntl = 0
	cntm = 0
	cnth = 0
	sum = 0
	target = []
	for lr in lra:
		if m > lr[1]:
			sum += lr[0]
			cntl += 1
		elif m < lr[0]:
			sum += lr[0]
			cnth += 1
		else:
			target.append(lr[0])
			cntm += 1
	mi = len(lra) // 2
	if cntl + cntm < mi:
		return True
	if cntm + cnth <= mi:
		return False
	need = mi - cntl
	for i in range(len(target)):
		if i < need:
			sum += target[i]
		else:
			sum += m
	return sum <= s
t = int(stdin.readline())
for i in range(t):
	ns = list(map(int, stdin.readline().split()))
	n = ns[0]
	s = ns[1]
	lra = []
	for j in range(n):
		lra.append(list(map(int, stdin.readline().split())))
	lra.sort(key=lambda x: x[0])
	res = getmaximummediansalary(lra, n, s)
	stdout.write(str(res) + '\n')


import sys
import bisect
input = sys.stdin.readline

def checker(rem_, lower_):
	sum_ = 0
	a = []
	b = []
	for i in range(n):
		if lower[i][1] >= rem_:
			a.append(lower[i][0])
		else:
			b.append(lower[i][0])
	a.sort(reverse=True)
	if len(a) > n // 2 and sum([max(j, rem_) for j in a[:n // 2 + 1]]) + sum(a[n // 2 + 1:]) + sum(b) <= s:
		return True
	return False
t = int(input())
for i in range(t):
	lower = []
	higher = []
	(n, s) = map(int, input().split())
	for i in range(n):
		(l, r) = map(int, input().split())
		lower.append([l, r])
		higher.append(l)
	higher.sort()
	if sum(higher) == s:
		print(higher[n // 2])
	else:
		beg = 1
		end = 1000000001
		while end - beg > 1:
			mid = (beg + end) // 2
			if checker(mid, lower):
				beg = mid
			else:
				end = mid
		print(beg)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, s) = map(int, input().split())
	lr = [list(map(int, input().split())) for i in range(n)]
	ng = 10 ** 9 + 1
	ok = 0
	while ng - ok > 1:
		mid = (ok + ng) // 2
		cnt_more = 0
		ss = 0
		v = []
		for (l, r) in lr:
			if mid <= l:
				cnt_more += 1
				ss += l
			elif l < mid <= r:
				v.append(l)
			else:
				ss += l
		v.sort()
		need = max(0, n // 2 + 1 - cnt_more)
		if len(v) < need:
			ng = mid
			continue
		for i in range(len(v)):
			if i < len(v) - need:
				ss += v[i]
			else:
				ss += mid
		if ss <= s:
			ok = mid
		else:
			ng = mid
	print(ok)


import sys, os, io
input = sys.stdin.readline
PI = 3.141592653589793
INF = float('inf')
MOD = 1000000007

def bin32(num):
	return '{0:032b}'.format(num)

def add(x, y):
	return (x + y) % MOD

def sub(x, y):
	return (x - y + MOD) % MOD

def mul(x, y):
	return x * y % MOD

def gcd(x, y):
	if y == 0:
		return x
	return gcd(y, x % y)

def lcm(x, y):
	return x * y // gcd(x, y)

def power(x, y):
	res = 1
	x %= MOD
	while y != 0:
		if y & 1:
			res = mul(res, x)
		y >>= 1
		x = mul(x, x)
	return res

def mod_inv(n):
	return power(n, MOD - 2)

def prob(p, q):
	return mul(p, power(q, MOD - 2))

def ii():
	return int(input())

def li():
	return [int(i) for i in input().split()]

def ls():
	return [i for i in input().split()]
for t in range(ii()):
	t += 1
	(n, s) = li()
	store = []
	l = [0 for i in range(n)]
	r = [0 for i in range(n)]
	for i in range(n):
		(l[i], r[i]) = li()
		store.append([l[i], r[i]])
	store.sort()
	store.reverse()
	l.sort()
	L = l[n // 2]
	R = s + 1
	while R - L > 1:
		mid = (L + R + 1) // 2
		sal = 0
		cnt = 0
		for i in range(n):
			if store[i][0] <= mid <= store[i][1]:
				if cnt < n // 2 + 1:
					cnt += 1
					sal += mid
				else:
					sal += store[i][0]
			elif store[i][0] > mid:
				cnt += 1
				sal += store[i][0]
			elif store[i][1] < mid:
				sal += store[i][0]
		if sal <= s and cnt == n // 2 + 1:
			L = mid
		else:
			R = mid
	print(L)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)

def ctd(chr):
	return ord(chr) - ord('a')
mod = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		(n, s) = RL()
		arr = [RLL() for _ in range(n)]
		mid = n // 2 + 1

		def c(num):
			now = 0
			total = 0
			tmp = []
			for (l, r) in arr:
				if r < num:
					total += l
				elif l > num:
					total += l
					now += 1
				else:
					tmp.append([l, r])
			dif = mid - now
			tmp.sort(key=lambda a: a[0], reverse=1)
			for i in range(len(tmp)):
				if i + 1 <= dif:
					total += num
					now += 1
				else:
					total += tmp[i][0]
			return now >= mid and total <= s
		(l, r) = (0, s)
		while l < r:
			m = (l + r + 1) // 2
			if c(m):
				l = m
			else:
				r = m - 1
		print(l)
main()


import sys
input = sys.stdin.readline
test = int(input())
for i in range(test):
	numbers = list(map(int, input().split()))
	people = numbers[0]
	salary = numbers[1]
	interv = []
	nr = 0
	for j in range(people):
		v = list(map(int, input().split()))
		left = v[0]
		right = v[1]
		nr = nr + left
		interv.append([left, right])
	left = 0
	right = 1000000001
	while right > left + 1:
		m = (left + right) // 2
		fin = []
		for j in range(people):
			if m <= interv[j][1]:
				if -interv[j][0] < -m:
					fin.append(-m)
				else:
					fin.append(-interv[j][0])
		x = len(fin)
		if x < people // 2 + 1:
			right = m
			continue
		fin.sort()
		suma = nr + (people // 2 + 1) * m + sum(fin[:people // 2 + 1])
		if suma > salary:
			right = m
		else:
			left = m
	print(left)


import sys
input = sys.stdin.readline
import heapq as hq
t = int(input())
for _ in range(t):
	(n, s) = map(int, input().split())
	sr = [list(map(int, input().split())) for i in range(n)]
	summn = sum(list(zip(*sr))[0])
	med = n // 2 + 1
	l = 0
	r = s + 1
	while l + 1 < r:
		flg = 0
		x = (l + r) // 2
		cost = summn
		q = []
		hq.heapify(q)
		for i in range(n):
			if sr[i][1] >= x:
				hq.heappush(q, -sr[i][0])
		if len(q) < med:
			pass
		else:
			for _ in range(med):
				cost += max(0, x + hq.heappop(q))
			if cost <= s:
				flg = 1
		if flg:
			l = x
		else:
			r = x
	print(l)


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, s) = [int(i) for i in input().split()]
	l = []
	r = []
	v = []
	for i in range(n):
		(li, ri) = [int(i) for i in input().split()]
		l.append(li)
		r.append(ri)
		v.append([li, ri])
	l.sort()
	r.sort()
	v.sort()
	low = l[n // 2]
	high = r[n // 2]
	while low < high:
		mid = (low + high + 1) // 2
		curr = []
		cost = 0
		rem = []
		for i in range(n):
			if v[i][1] < mid:
				curr.append(v[i])
			else:
				rem.append(v[i])
		curr.extend(rem)
		for i in range(n):
			if i < n // 2:
				cost += curr[i][0]
			else:
				cost += max(mid, curr[i][0])
		if cost <= s:
			low = mid
		else:
			high = mid - 1
	print(low)


import sys
readline = sys.stdin.readline
read = sys.stdin.read
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
	(n, s) = nm()
	m = (n + 1) // 2
	emp = [tuple(nm()) for _ in range(n)]
	emp.sort(reverse=True)
	ok = emp[m - 1][0]
	ng = s + 1
	while ng - ok > 1:
		x = (ok + ng) // 2
		cur = 0
		t = 0
		for (l, r) in emp:
			if r >= x and t < m:
				cur += max(x, l)
				t += 1
			else:
				cur += l
		if t == m and cur <= s:
			ok = x
		else:
			ng = x
	print(ok)
	return
T = ni()
for _ in range(T):
	solve()


import sys
input = sys.stdin.readline

def judge(x):
	salary = []
	(left, right) = (0, 0)
	l = []
	for (li, ri) in lr:
		if ri < x:
			salary.append(li)
			left += 1
		elif x < li:
			salary.append(li)
			right += 1
		else:
			l.append((li, ri))
	if left > (n - 1) // 2 or right > (n - 1) // 2:
		return False
	l.sort(key=lambda k: k[0])
	for i in range(len(l)):
		if i < (n - 1) // 2 - left:
			salary.append(l[i][0])
		else:
			salary.append(x)
	return sum(salary) <= s

def binary_search(l):
	r = 10 ** 10
	while l <= r:
		mid = (l + r) // 2
		if judge(mid):
			l = mid + 1
		else:
			r = mid - 1
	return r
t = int(input())
for _ in range(t):
	(n, s) = map(int, input().split())
	lr = [tuple(map(int, input().split())) for _ in range(n)]
	ls = [li for (li, _) in lr]
	ls.sort()
	ans = binary_search(ls[n // 2])
	print(ans)


import sys
INF = 10 ** 9
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.buffer.readline
t = int(input())
for i in range(t):
	(n, s) = [int(item) for item in input().split()]
	lr = []
	for j in range(n):
		(l, r) = [int(item) for item in input().split()]
		lr.append((l, r))
	lft = 0
	rgt = 10 ** 9 + 1
	while rgt - lft > 1:
		mid = (lft + rgt) // 2
		minimum_cost = 0
		takable = []
		for (l, r) in lr:
			minimum_cost += l
			if mid <= r:
				takable.append(max(l - mid, 0) - l)
		if len(takable) < n // 2 + 1:
			rgt = mid
			continue
		takable.sort()
		cost = sum(takable[:n // 2 + 1]) + minimum_cost + mid * (n // 2 + 1)
		if cost <= s:
			lft = mid
		else:
			rgt = mid
	print(lft)


from sys import stdin
t = int(stdin.readline())
for _ in range(t):
	(n, s) = map(int, stdin.readline().split())
	lr = [list(map(int, stdin.readline().split())) for i in range(n)]
	lr.sort(reverse=True)
	l = 0
	r = s + 1
	while l + 1 < r:
		mid = (l + r) // 2
		right_cnt = 0
		salary = 0
		for p in lr:
			if p[0] > mid:
				right_cnt += 1
				salary += p[0]
			elif p[0] <= mid <= p[1]:
				if right_cnt < (n + 1) // 2:
					right_cnt += 1
					salary += mid
				else:
					salary += p[0]
			elif mid > p[1]:
				salary += p[0]
		if salary <= s and right_cnt >= (n + 1) // 2:
			l = mid
		else:
			r = mid
	print(l)


import sys
input = sys.stdin.readline
t = int(input())
while t > 0:
	t -= 1
	(n, ss) = map(int, input().split())
	lr = []
	sl = 0
	for i in range(n):
		(l, r) = map(int, input().split())
		sl += l
		lr.append([l, r])
	l = 0
	r = 10 ** 9 + 1
	while r - l > 1:
		mid = (r + l) // 2
		s = []
		for i in range(n):
			if mid <= lr[i][1]:
				s.append(max(-lr[i][0], -mid))
		if len(s) < n // 2 + 1:
			r = mid
			continue
		s.sort()
		sumi = sl + (n // 2 + 1) * mid + sum(s[:n // 2 + 1])
		if sumi > ss:
			r = mid
		else:
			l = mid
	print(l)


import os

def binary_search(f, low, high):
	mid = (high + low) // 2
	if low == high:
		return low
	if f(mid):
		return binary_search(f, mid + 1, high)
	else:
		return binary_search(f, low, mid)

def f(lr, k, s):
	d1s = 0
	d1c = 0
	d3s = 0
	d3c = 0
	n = len(lr)
	d2cs = [0]
	for (l, r) in lr:
		if r < k:
			d1s += l
			d1c += 1
		elif k < l:
			d3s += l
			d3c += 1
		else:
			d2cs.append(d2cs[-1] + l)
	if n // 2 < d1c:
		return False
	spend = d1s + d2cs[n // 2 - d1c] + max((n + 1) // 2 - d3c, 0) * k + d3s
	return spend <= s

def m(lr, s):
	if len(lr) == 1:
		return min(s, lr[0][1])
	lr = sorted(lr)
	k_low = lr[len(lr) // 2][0]
	return binary_search(lambda k: f(lr, k, s), k_low, max((r for (l, r) in lr)) + 1) - 1

def pp(input):
	n_test = int(input())
	for i in range(n_test):
		(n, s) = map(int, input().split())
		lr = [tuple(map(int, input().split())) for _ in range(n)]
		print(m(lr, s))
if 'paalto' in os.getcwd():
	from string_source import string_source
	s0 = string_source('3\n3 26\n10 12\n1 4\n10 11\n1 1337\n1 1000000000\n5 26\n4 4\n2 4\n6 8\n5 6\n2 7')
	pp(s0)
	s1 = string_source('1\n19 1175\n44 87\n68 100\n93 98\n76 79\n10 58\n74 99\n87 97\n23 75\n62 73\n100 100\n71 76\n73 87\n76 82\n44 84\n54 90\n2 82\n67 99\n85 97\n66 88')
	pp(s1)
else:
	pp(input)