Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly $n$ flowers.

Vladimir went to a flower shop, and he was amazed to see that there are $m$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the $i$-th type happiness of his wife increases by $a_i$ and after receiving each consecutive flower of this type her happiness increases by $b_i$. That is, if among the chosen flowers there are $x_i > 0$ flowers of type $i$, his wife gets $a_i + (x_i - 1) \cdot b_i$ additional happiness (and if there are no flowers of type $i$, she gets nothing for this particular type).

Please help Vladimir to choose exactly $n$ flowers to maximize the total happiness of his wife.


-----Input-----

The first line contains the only integer $t$ ($1 \leq t \leq 10\,000$), the number of test cases. It is followed by $t$ descriptions of the test cases.

Each test case description starts with two integers $n$ and $m$ ($1 \le n \le 10^9$, $1 \le m \le 100\,000$), the number of flowers Vladimir needs to choose and the number of types of available flowers.

The following $m$ lines describe the types of flowers: each line contains integers $a_i$ and $b_i$ ($0 \le a_i, b_i \le 10^9$) for $i$-th available type of flowers.

The test cases are separated by a blank line. It is guaranteed that the sum of values $m$ among all test cases does not exceed $100\,000$.


-----Output-----

For each test case output a single integer: the maximum total happiness of Vladimir's wife after choosing exactly $n$ flowers optimally.


-----Example-----
Input
2
4 3
5 0
1 4
2 2

5 3
5 2
4 2
3 1

Output
14
16



-----Note-----

In the first example case Vladimir can pick 1 flower of the first type and 3 flowers of the second type, in this case the total happiness equals $5 + (1 + 2 \cdot 4) = 14$.

In the second example Vladimir can pick 2 flowers of the first type, 2 flowers of the second type, and 1 flower of the third type, in this case the total happiness equals $(5 + 1 \cdot 2) + (4 + 1 \cdot 2) + 3 = 16$.

Source: codeforces | Difficulty: HARD
Tags: Graph traversal

Sorting

Amortized analysis

Greedy algorithms

Complete search

Dynamic programming

Data structures


Solutions:
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(N, M) = map(int, input().split())
	table = [0] * M
	t = []
	for i in range(M):
		(a, b) = map(int, input().split())
		t.append((a, b))
	cs = [0] * (M + 1)
	t.sort(key=lambda x: -x[0])
	for i in range(M):
		cs[i + 1] = cs[i] + t[i][0]
	res = cs[min(N, M)]
	for i in range(M):
		x = t[i][1]
		ok = 0
		ng = min(N, M) + 1
		while ng - ok > 1:
			m = (ok + ng) // 2
			if t[m - 1][0] > x:
				ok = m
			else:
				ng = m
		if ok - 1 >= i:
			res = max(res, cs[ok] + (N - ok) * x)
		elif N - ok > 0:
			res = max(res, cs[ok] + t[i][0] + (N - ok - 1) * x)
	print(res)
	input()


import sys
input = sys.stdin.buffer.readline
from bisect import bisect_left

def solve(N, M, AB):
	As = []
	for (a, _) in AB:
		As.append(a)
	As.sort()
	sA = [0]
	for a in As:
		sA.append(a + sA[-1])
	ans = sA[-1] - sA[-1 - min(M, N)]
	for (a, b) in AB:
		ind = bisect_left(As, b)
		countA = M - ind
		if a >= b:
			countA = min(countA, N)
			score = sA[-1] - sA[-1 - countA] + (N - countA) * b
		else:
			countA = min(countA, N - 1)
			score = a + sA[-1] - sA[-1 - countA] + (N - countA - 1) * b
		ans = max(ans, score)
	return ans
Q = int(input())
for q in range(Q):
	(N, M) = map(int, input().split())
	AB = [list(map(int, input().split())) for _ in range(M)]
	if q != Q - 1:
		input()
	print(solve(N, M, AB))


import sys
input = sys.stdin.readline
t = int(input())
for tc in range(t):
	if tc:
		input()
	(n, m) = map(int, input().split())
	a = [-1] * m
	b = [-1] * m
	for j in range(m):
		(a[j], b[j]) = map(int, input().split())
	l = [(a[i], 0, i) for i in range(m)] + [(b[i], 1, i) for i in range(m)]
	l.sort(reverse=True)
	used = [False] * m
	count = 0
	tot = 0
	best = 0
	for (good, typ, ind) in l:
		if typ == 0:
			count += 1
			tot += good
			used[ind] = True
			if count == n:
				best = max(best, tot)
				break
		else:
			curr = tot
			curr += good * (n - count)
			if not used[ind]:
				curr -= good
				curr += a[ind]
			best = max(curr, best)
	print(best)


import sys
input = sys.stdin.readline
test = int(input())
for nt in range(test):
	(n, m) = map(int, input().split())
	a = []
	b = []
	for i in range(m):
		(x, y) = map(int, input().split())
		a.append((x, i))
		b.append((y, x, i))
	a.sort(reverse=True)
	b.sort(reverse=True)
	i = 0
	ans = 0
	s = 0
	done = {}
	for j in range(m):
		while n and i < m and (a[i][0] > b[j][0]):
			n -= 1
			s += a[i][0]
			done[a[i][1]] = 1
			i += 1
		if n:
			if b[j][2] not in done:
				ans = max(ans, s + b[j][1] + b[j][0] * (n - 1))
			else:
				ans = max(ans, b[j][0] * n + s)
		else:
			ans = max(ans, s)
	print(ans)
	if nt != test - 1:
		input()


import sys
import re

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	s = minp()
	while s == '':
		s = minp()
	(n, m) = map(int, s.split())
	a = [0] * m
	best = (-1, -1, -1)
	for i in range(m):
		(x, y) = mints()
		a[i] = (x, y)
	a.sort()
	for i in range(m):
		(x, y) = a[i]
		best = max(best, (y, x, i))
	p = [0] * (m + 1)
	for i in range(1, m + 1):
		p[i] = p[i - 1] + a[i - 1][0]
	a1 = p[m] - p[max(m - n, 0)] + max(n - m, 0) * best[0]
	if n < 1:
		print(a1)
	for ii in range(m):
		a2 = (n - 1) * a[ii][1] + a[ii][0]
		b = a[ii][1]
		(l, r) = (-1, m)
		while r - l > 1:
			c = (l + r) // 2
			if a[c][0] > b:
				r = c
			else:
				l = c
		r = max(m - (n - 1), r)
		if r <= ii:
			a2 += -(m - r) * b + p[m] - p[r] + a[ii][1] - a[ii][0]
		else:
			a2 += -(m - r) * b + p[m] - p[r]
		a1 = max(a1, a2)
	print(a1)
for i in range(mint()):
	solve()


t = int(input())
for test in range(t):
	if test != 0:
		s = input()
	(n, m) = map(int, input().split())
	(a, b) = ([0] * m, [0] * m)
	sor = []
	for i in range(m):
		(a[i], b[i]) = map(int, input().split())
		sor.append((a[i], 0, i))
		sor.append((b[i], 1, i))
	sor.sort(reverse=True)
	(ans, cur, cnt) = (0, 0, 0)
	vis = [0] * m
	for (x, typ, i) in sor:
		if typ == 0:
			cur += x
			cnt += 1
			vis[i] = 1
			if cnt == n:
				ans = max(ans, cur)
				break
		else:
			temp = cur + x * (n - cnt)
			if not vis[i]:
				temp -= x
				temp += a[i]
			ans = max(ans, temp)
	print(ans)


import sys
input = sys.stdin.readline

def binary_search(list, item):
	low = 0
	high = len(list) - 1
	while low <= high:
		mid = (low + high) // 2
		guess = list[mid][0]
		if guess == item:
			return mid
		if guess < item:
			high = mid - 1
		else:
			low = mid + 1
	else:
		return low
for i in range(int(input())):
	if i:
		input()
	(n, m) = list(map(int, input().split()))
	d = [0] * m
	for j in range(m):
		d[j] = tuple(map(int, input().split()))
	d.sort(reverse=True)
	pre_d = [0] * m
	pre_d[0] = d[0][0]
	for j in range(1, m):
		pre_d[j] = pre_d[j - 1] + d[j][0]
	s = 0
	b_max = 0
	for j in range(m):
		if d[j][1] > b_max:
			fin = binary_search(d, d[j][1])
			if fin:
				if fin > j:
					if fin <= n:
						s_temp = pre_d[fin - 1] + d[j][1] * (n - fin)
					else:
						s_temp = pre_d[n - 1]
				elif fin <= n - 1:
					s_temp = pre_d[fin - 1] + d[j][0] + d[j][1] * (n - 1 - fin)
				else:
					s_temp = pre_d[n - 1]
			else:
				s_temp = d[j][0] + d[j][1] * (n - 1)
			if s_temp > s:
				s = s_temp
				b_max = d[j][1]
	print(s)


import sys
import bisect
input = sys.stdin.readline

def solve():
	(n, m) = map(int, input().split())
	F = [None] * m
	for i in range(m):
		(a, b) = map(int, input().split())
		F[i] = (a, b)
	F.sort()
	A = [a for (a, _) in F]
	B = [b for (_, b) in F]
	suff = A[:]
	for i in range(m - 2, -1, -1):
		suff[i] += suff[i + 1]
	if m >= n:
		ans = suff[m - n]
	else:
		ans = -1 << 32
	for i in range(m):
		idx = bisect.bisect_left(A, B[i])
		if idx == m:
			ans = max(ans, A[i] + (n - 1) * B[i])
			continue
		if m - idx <= n - 1:
			case = suff[idx] + A[i] + (n - m + idx - 1) * B[i]
			if A[i] >= B[i]:
				case += B[i] - A[i]
			ans = max(ans, case)
	return ans
for nt in range(int(input())):
	print(solve())
	input()


from bisect import bisect_left
t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	ab = [list(map(int, input().split())) for _ in range(m)]
	aa = [e for (e, _) in ab]
	aa.sort()
	acc = [0] * (m + 1)
	for i in range(m, 0, -1):
		acc[i - 1] = acc[i] + aa[i - 1]
	if n > m:
		ans = 0
	else:
		ans = sum(aa[-n:])
	for (a, b) in ab:
		i = bisect_left(aa, b)
		cnt = min(m - i, n)
		sm = acc[m - cnt]
		sm += b * (n - cnt)
		if a < b:
			sm -= b
			sm += a
		ans = max(ans, sm)
	print(ans)
	if case != t - 1:
		input()


import sys
import bisect
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		(N, M) = [int(x) for x in input().split()]
		AB = [[int(x) for x in input().split()] for _ in range(M)]
		A = []
		for (a, b) in AB:
			A.append(a)
		A.sort()
		ruiseki = [0] * M
		for (i, a) in enumerate(A[::-1]):
			ruiseki[i] = ruiseki[i - 1] + a
		ans = 0
		for (a, b) in AB:
			x = M - bisect.bisect_right(A, b)
			if x >= 1:
				tmp = ruiseki[min(x, N) - 1]
			else:
				tmp = 0
			if x <= N and a > b and (a >= A[-x]):
				tmp -= a
				x -= 1
			if N > x:
				tmp += a + b * (N - x - 1)
			ans = max(ans, tmp)
		print(ans)
		if _ != t - 1:
			S = input()
main()


from bisect import bisect_left
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	F = []
	A = []
	B = []
	for i in range(m):
		(a, b) = list(map(int, input().split()))
		A.append(a)
		B.append(b)
		F.append((a, b))
	A.sort()
	A_copy = A[:]
	A_copy.sort()
	A_cumul = [0]
	non = input()
	for i in range(0, len(A_copy)):
		A_cumul.append(A_cumul[-1] + A_copy[i])
	B.sort(reverse=True)
	ans = sum(A[:n]) + B[0] * (n - m)
	for (a, b) in F:
		ind = bisect_left(A, b)
		cnt = min(m - ind, n)
		temp = A_cumul[m] - A_cumul[m - cnt] + b * (n - cnt)
		if a < b and n - cnt != 0:
			temp += a
			temp -= b
		ans = max(temp, ans)
	print(ans)


import bisect
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	flowers = []
	flowers_a = []
	max_b = 0
	for i in range(m):
		(a, b) = map(int, input().split())
		flowers.append((a, b))
	flowers.sort()
	flowers_b = []
	for i in range(m):
		flowers_a.append(flowers[i][0])
		flowers_b.append(flowers[i][1])
	val = 0
	prefix_sum = [0]
	for x in flowers_a:
		prefix_sum.append(prefix_sum[-1] + x)
	for i in range(m):
		idx = bisect.bisect_left(flowers_a, flowers_b[i])
		options = m - idx
		if options >= n:
			temp = prefix_sum[-1] - prefix_sum[-n - 1]
			val = max(val, temp)
			continue
		else:
			temp = prefix_sum[-1] - prefix_sum[-options - 1]
			remaining = n - options
			if idx <= i:
				temp += flowers_b[i] * remaining
			else:
				temp += flowers_a[i] + flowers_b[i] * (remaining - 1)
			val = max(val, temp)
	print(val)
	if _ != t - 1:
		blank_line = input()


for _ in range(int(input())):
	if _:
		input()
	(n, m) = map(int, input().split())
	a1 = sorted((tuple(map(int, input().split())) for i in range(m)), reverse=True)
	a2 = sorted(a1, key=lambda x: x[1], reverse=True)
	a1.append((0, 0))
	r = 0
	s = 0
	ans = 0
	for (x, y) in a2:
		while r < n - 1 and a1[r][0] > y:
			s += a1[r][0]
			r += 1
		if x > y and a1[r][0] < x:
			cs = s + (n - r) * y
		else:
			cs = s + x + (n - r - 1) * y
		ans = max(cs, ans)
	print(ans, flush=False)


import sys

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

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for test in range(testCases):
	(n, m) = input_split()
	arr = []
	barr = []
	for _ in range(m):
		(a, b) = input_split()
		arr.append(a)
		barr.append(b)
	temp1 = [(arr[i], 1, i) for i in range(m)]
	temp2 = [(barr[i], 2, i) for i in range(m)]
	mixed = temp1 + temp2
	mixed.sort()
	mixed.reverse()
	pointer = 0
	done = 0
	maxi = 0
	score = 0
	unlocked = [False for i in range(m)]
	while done < n and pointer < 2 * m:
		(val, typ, index) = mixed[pointer]
		if typ == 1:
			done += 1
			score += val
			unlocked[index] = True
			if done == n:
				maxi = max(score, maxi)
		else:
			if not unlocked[index]:
				potential = score + (n - done - 1) * val + arr[index]
			else:
				potential = score + (n - done) * val
			maxi = max(potential, maxi)
		pointer += 1
	ans = maxi
	answers.append(ans)
	if test != testCases - 1:
		blank = input()
print(*answers, sep='\n')


import bisect as bi, sys
import math as mt
import collections as cc
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	if tc > 0:
		input()
	(n, m) = I()
	a = [0] * m
	b = [0] * m
	sor = []
	for i in range(m):
		(a[i], b[i]) = I()
		sor.append((a[i], 0, i))
		sor.append((b[i], 1, i))
	sor.sort(reverse=True)
	ans = 0
	cur = 0
	cnt = 0
	visi = [0] * m
	for (x, ty, ind) in sor:
		if ty == 0:
			cur += x
			cnt += 1
			visi[ind] = 1
			if cnt == n:
				ans = max(ans, cur)
				break
		else:
			temp = cur + x * (n - cnt)
			if not visi[ind]:
				temp -= x
				temp += a[ind]
			ans = max(ans, temp)
	print(ans)


from bisect import bisect_left
from itertools import accumulate

def main():
	(n, m) = map(int, input().split())
	(a, b) = zip(*sorted((tuple((int(x) for x in input().split())) for _ in range(m))))
	sums = list(reversed(list(accumulate(reversed(a)))))
	sums.append(0)
	ans = 0
	for i in range(m):
		pos = bisect_left(a, b[i])
		if m - pos > n:
			pos = m - n
		if m - pos == n and pos > i:
			pos += 1
		suf = sums[pos]
		cnt = m - pos
		if pos > i:
			suf += a[i]
			cnt += 1
		res = suf + (n - cnt) * b[i]
		ans = max(ans, res)
	print(ans)
tests = int(input())
for t in range(tests):
	if t > 0:
		input()
	main()


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

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

def main():
	T = int(input())
	for x in range(T):
		(N, M) = getlist()
		ans = 0
		AB = []
		for i in range(M):
			(a, b) = getlist()
			AB.append([a, b])
		AB.sort()
		A = [AB[i][0] for i in range(M)]
		B = [AB[i][1] for i in range(M)]
		Asum = [0] * (M + 1)
		for i in range(M):
			Asum[i + 1] += Asum[i] + A[i]
		if N <= M:
			for i in range(N):
				ans += A[-1 - i]
		for i in range(M):
			b = B[i]
			itr = bisect.bisect_left(A, b + 1)
			if itr > i and M - itr <= N - 2:
				pre1 = Asum[-1] - Asum[itr]
				pre2 = A[i] + B[i] * (N - M + itr - 1)
				ans = max(ans, pre1 + pre2)
			if itr <= i and M - itr <= N - 1:
				pre1 = Asum[-1] - Asum[itr]
				pre2 = B[i] * (N - M + itr)
				ans = max(ans, pre1 + pre2)
		print(ans)
		if x < T - 1:
			mar = input()
main()


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import heapq
t = int(input())
for index123 in range(t):
	(n, m) = map(int, input().split())
	flowerHappiness = []
	for _ in range(m):
		(a, b) = map(int, input().split())
		flowerHappiness.append((a, b))
	if index123 != t - 1:
		input()
	flowerHappiness.sort(key=lambda x: x[1], reverse=True)
	flowerHappiness.sort(key=lambda x: x[0], reverse=True)
	maxHappiness = 0
	if n <= m:
		happinessCur = 0
		for i in range(n):
			happinessCur += flowerHappiness[i][0]
		maxHappiness = happinessCur
	index = min(n, m - 1)
	sumUpToIndex = 0
	for i in range(index + 1):
		sumUpToIndex += flowerHappiness[i][0]
	curBMax = 0
	for i in range(m):
		if flowerHappiness[i][1] > curBMax:
			curBMax = flowerHappiness[i][1]
			happinessCur = flowerHappiness[i][1] * (n - 1) + flowerHappiness[i][0]
			while index >= 0 and flowerHappiness[index][0] < flowerHappiness[i][1]:
				sumUpToIndex -= flowerHappiness[index][0]
				index -= 1
			if index != -1:
				happinessCur += sumUpToIndex - (index + 1) * flowerHappiness[i][1]
				if index == n:
					happinessCur = sumUpToIndex - flowerHappiness[index][0]
				elif index >= i:
					happinessCur -= flowerHappiness[i][0]
					happinessCur += flowerHappiness[i][1]
			if happinessCur > maxHappiness:
				maxHappiness = happinessCur
	print(maxHappiness)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n, m) = I()
	l = []
	b = []
	vis = [0] * m
	for i in range(m):
		l.append(I())
	input()
	l.sort(reverse=True)
	for i in range(m):
		b.append([l[i][1], i])
	b.sort(reverse=True, key=lambda x: [x[0], -x[1]])
	an = s = ct = 0
	cr = 0
	for i in range(m):
		while cr < n and (cr < m and l[cr][0] > b[i][0]):
			s += l[cr][0]
			cr += 1
		if cr < n:
			an = max(an, s + ((n - cr) * b[i][0] if cr > b[i][1] else (n - cr - 1) * b[i][0] + l[b[i][1]][0]))
		elif cr == n:
			an = max(an, s)
		else:
			break
	print(an)


import sys
import math
from collections import defaultdict, Counter
import operator, bisect
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
t = int(input())
for i in range(t):
	if i != 0:
		s = input()
	(n, m) = map(int, input().split())
	l1 = []
	l2 = []
	for j in range(m):
		(a, b) = map(int, input().split())
		l1.append(a)
		l2.append([b, a])
	l1.sort()
	d = [0] * m
	d[0] = l1[-1]
	for j in range(1, m):
		d[j] = d[j - 1] + l1[-(j + 1)]
	ans = 0
	for j in l2:
		ind = m - bisect.bisect_left(l1, j[0])
		need = n - ind
		if need > 0:
			if ind > 0:
				s1 = d[ind - 1]
			else:
				s1 = 0
			if j[1] >= j[0]:
				s1 += need * j[0]
			else:
				s1 += (need - 1) * j[0] + j[1]
		else:
			s1 = d[n - 1]
		ans = max(ans, s1)
	print(ans)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	arr = []
	for __ in range(m):
		(a, b) = [int(x) for x in input().split()]
		arr.append((a, b))
	if _ != t - 1:
		input()
	arr.sort(reverse=True)
	p = []
	total = 0
	for i in range(m):
		total += arr[i][0]
		p.append(total)
	ans = -float('inf')
	for i in range(m):
		(a, b) = arr[i]
		idx = -1
		c = m
		while c > 0:
			while idx + c < m and arr[idx + c][0] > b:
				idx += c
			c //= 2
		idx = min(idx, n - 1)
		if n - 1 == idx and i > idx:
			idx -= 1
		if idx == -1:
			prefSum = 0
		else:
			prefSum = p[idx]
		nB = n - (idx + 1)
		if i > idx:
			nB -= 1
			ans = max(ans, prefSum + a + b * nB)
		else:
			ans = max(ans, prefSum + b * nB)
	print(ans)


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')
from fractions import Fraction
INF = float('inf')
mod = int(1000000000.0) + 7
T = int(data())
for t in range(T):
	(n, m) = mdata()
	(a, b) = ([], [])
	k = min(n, 100000)
	ind = 0
	for i in range(m):
		(a1, b1) = mdata()
		a.append(a1)
		b.append(b1)
	a1 = sorted(a)
	s = [0] * m
	s[0] = a1[-1]
	ans = 0
	for i in range(m - 2, -1, -1):
		s[m - i - 1] = s[m - i - 2] + a1[i]
	for i in range(m):
		k1 = bl(a1, b[i])
		k1 -= 1
		if b[i] <= a[i]:
			ans1 = max(0, n - (m - k1 - 1)) * b[i]
			if m - k1 - 2 > -1:
				ans1 += s[min(n - 1, m - k1 - 2)]
		else:
			ans1 = a[i] + max(0, n - 1 - (m - k1 - 1)) * b[i]
			if min(n - 2, m - k1 - 2) >= 0:
				ans1 += s[min(n - 2, m - k1 - 2)]
		ans = max(ans, ans1)
	out(ans)
	if t != T - 1:
		s = data()


import bisect, sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	A = []
	B = []
	for i in range(m):
		(a, b) = map(int, input().split())
		A.append([a, b])
		B.append(a)
	B.sort()
	C = [0 for i in range(m + 1)]
	for i in range(m - 1, -1, -1):
		C[i] = B[i] + C[i + 1]
	ans = 0
	if n <= m:
		for i in range(m - 1, m - n - 1, -1):
			ans = ans + B[i]
	for i in range(m):
		v = bisect.bisect(B, A[i][1])
		sv = A[i][0]
		if m - v <= n - 1:
			rv = n - (m - v) - 1
			sv = sv + C[v] + rv * A[i][1]
			if v != m and A[i][0] >= B[v]:
				sv = sv - A[i][0] + A[i][1]
		ans = max(ans, sv)
	print(ans)
	av = input()


import sys
input = sys.stdin.readline
from bisect import bisect_right as br
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ab = sorted([list(map(int, input().split())) for i in range(m)])
	sa = [0]
	a = [0]
	for i in range(m):
		now = ab[i][0]
		a.append(now)
		sa.append(sa[-1] + now)
	ans = 0
	if n <= m:
		l = m - n + 1
	else:
		l = 0
	for i in range(m):
		(na, nb) = ab[i]
		ind = max(l, br(a, nb))
		count = sa[-1] - sa[ind - 1]
		left = n - (m + 1 - ind)
		if na < nb and left:
			count += na
			left -= 1
		count += left * nb
		ans = max(ans, count)
	print(ans)
	if _ != t - 1:
		s = input()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ls = []
	lst = []
	for __ in range(m):
		(a, b) = map(int, input().split())
		ls.append(a)
		z = (b, a)
		lst.append(z)
	ls.sort(reverse=True)
	lst.sort(reverse=True)
	(mx, ll, ii, happy) = (0, 0, 0, 0)
	for i in range(m):
		j = n - ll
		while ii < m and j and (ls[ii] > lst[i][0]):
			mx += ls[ii]
			ii += 1
			ll += 1
			j -= 1
		if j:
			happy = max(happy, mx + min(lst[i]) + (j - 1) * lst[i][0])
		else:
			happy = max(mx, happy)
		if n == ll:
			break
	print(happy)
	if _ != t - 1:
		input()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main():
	for t in range(int(input())):
		if t >= 1:
			input()
		(n, m) = map(int, input().split())
		a = []
		for i in range(m):
			(x, y) = map(int, input().split())
			a.append([x, i + 1, 'a'])
			a.append([y, i + 1, 'b', x])
		a.sort(reverse=True, key=lambda x: x[0])
		b = set()
		l = su = ma = i = 0
		while i < 2 * m and n - l > 0:
			if a[i][2] == 'a':
				su += a[i][0]
				b.add(a[i][1])
				l += 1
			elif a[i][1] in b:
				if ma < su + (n - l) * a[i][0]:
					ma = su + (n - l) * a[i][0]
			elif ma < su + (n - l - 1) * a[i][0] + a[i][3]:
				ma = su + (n - l - 1) * a[i][0] + a[i][3]
			i += 1
		if ma < su:
			ma = su
		print(ma)
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	if _:
		input()
	(n, m) = map(int, input().split())
	a = []
	b = []
	for i in range(m):
		(v1, v2) = map(int, input().split())
		a.append(v1)
		b.append((v2, v1))
	a.sort(reverse=True)
	b.sort(reverse=True)
	(s, l, v, c) = [0] * 4
	for i in range(m):
		t = n - l
		while c < m and t and (a[c] > b[i][0]):
			s += a[c]
			l += 1
			c += 1
			t -= 1
		if t:
			v = max(v, s + min(b[i]) + b[i][0] * (t - 1))
		else:
			v = max(v, s)
		if n == l:
			break
	print(v)


import bisect, sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ma = []
	for i in range(m):
		ma.append(list(map(int, input().split())))
	ar = [x[0] for x in ma]
	ar.sort()
	ans = 0
	pre = [0]
	for i in range(m):
		pre.append(pre[-1] + ar[i])
	for i in range(m):
		xx = ma[i][1]
		ind = bisect.bisect_left(ar, xx)
		count = min(m - ind, n)
		tem = pre[m] - pre[m - count] + xx * (n - count)
		if ma[i][1] > ma[i][0] and n - count != 0:
			tem += ma[i][0]
			tem -= xx
		ans = max(ans, tem)
	print(ans)
	xx = input()


for _ in range(int(input())):
	if _:
		input()
	(n, m) = map(int, input().split())
	fs = sorted((tuple(map(int, input().split())) for _ in range(m)), reverse=True)
	fy = sorted(fs, key=lambda x: x[1], reverse=True)
	fs.append((0, 0))
	curx = 0
	cursum = 0
	ans = 0
	for (x, y) in fy:
		while curx < n - 1 and fs[curx][0] > y:
			cursum += fs[curx][0]
			curx += 1
		if x > y and fs[curx][0] < x:
			cans = cursum + (n - curx) * y
		else:
			cans = cursum + x + (n - curx - 1) * y
		ans = max(ans, cans)
	print(ans, flush=False)


import sys
import collections

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

def split_input():
	return [int(i) for i in input().split()]
tests = int(input())
answers = []
for testnum in range(tests):
	(n, m) = split_input()
	l = []
	for i in range(m):
		l.append(split_input())
	if testnum != tests - 1:
		split_input()
	new_l = []
	for i in range(len(l)):
		new_l.append((l[i][0], 1))
		new_l.append((l[i][1], 0))
	new_l.sort()
	x = [0] * len(new_l)
	num = [0] * len(new_l)
	x[-1] = 0 if new_l[-1][1] == 0 else new_l[-1][0]
	num[-1] = new_l[-1][1]
	for i in range(len(x) - 2, -1, -1):
		if new_l[i][1] == 1:
			x[i] = x[i + 1] + new_l[i][0]
		else:
			x[i] = x[i + 1]
		num[i] = num[i + 1] + new_l[i][1]
	suma = {}
	numa = {}
	for i in range(len(x)):
		if new_l[i][1] == 0:
			suma[new_l[i][0]] = x[i]
			numa[new_l[i][0]] = num[i]
	ans = 0
	picked = 0
	for i in range(len(new_l) - 1, -1, -1):
		if new_l[i][1] == 1:
			ans += new_l[i][0]
			picked += 1
		if picked == n:
			break
	for i in range(m):
		number = numa[l[i][1]]
		if n > number:
			if l[i][0] >= l[i][1]:
				ans = max(ans, suma[l[i][1]] + (n - number) * l[i][1])
			else:
				ans = max(ans, suma[l[i][1]] + l[i][0] + (n - number - 1) * l[i][1])
	answers.append(ans)
print(*answers, sep='\n')


import sys
from bisect import bisect
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def solve():
	aa = []
	for (a, b) in sorted(ab, reverse=True):
		aa.append(a)
	cs = [0]
	for a in aa:
		cs.append(cs[-1] + a)
	aa.reverse()
	cs.reverse()
	ans = cs[m - n] if m - n >= 0 else 0
	for (a, b) in ab:
		i = bisect(aa, b)
		if n - (m - i) - 1 < 0:
			continue
		if a > b:
			cur = cs[i] + (n - (m - i)) * b
		else:
			cur = cs[i] + a + (n - (m - i) - 1) * b
		ans = max(ans, cur)
	print(ans)
case = II()
for q in range(case):
	(n, m) = MI()
	ab = LLI(m)
	if q < case - 1:
		SI()
	solve()


import sys
inpy = [int(x) for x in sys.stdin.read().split()]
t = inpy[0]
index = 1
for _ in range(t):
	(n, m) = (inpy[index], inpy[index + 1])
	index += 2
	(a, b) = ([0] * m, [[0, 0] for _ in range(m)])
	for i in range(m):
		a[i] = inpy[index]
		b[i] = (inpy[index + 1], inpy[index])
		index += 2
	a.sort(reverse=True)
	b.sort(reverse=True)
	(res, cur, j) = (0, 0, 0)
	for i in range(m):
		while j < m and n > 0 and (b[i][0] < a[j]):
			cur += a[j]
			j += 1
			n -= 1
		if n == 0:
			res = max(res, cur)
			break
		if b[i][1] > b[i][0]:
			res = max(res, cur + b[i][0] * n)
		else:
			res = max(res, cur + b[i][1] + b[i][0] * (n - 1))
	print(res)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t1 = int(input())
for _ in range(t1):
	(n, m) = map(int, input().split())
	flowers = []
	visited = set()
	ans = 0
	for i in range(m):
		(a, b) = map(int, input().split())
		flowers.append([a, b, i])
	flowers1 = sorted(flowers, key=lambda student: student[1])
	flowers1.reverse()
	flowers2 = sorted(flowers, key=lambda student: student[0])
	flowers2.reverse()
	pointer = -1
	currsum = 0
	for i in range(m):
		t = flowers1[i]
		if pointer == -1:
			if flowers2[0][0] >= t[1]:
				pointer = 0
				currsum += flowers2[0][0]
				visited.add(flowers2[0][2])
		if pointer != -1:
			while pointer < n - 1 and pointer < m - 1 and (flowers2[pointer + 1][0] >= t[1]):
				pointer += 1
				currsum += flowers2[pointer][0]
				visited.add(flowers2[pointer][2])
		if t[2] in visited:
			ans = max(ans, currsum + t[1] * (n - pointer - 1))
		elif pointer == n - 1:
			ans = max(ans, currsum)
		else:
			ans = max(ans, currsum + t[0] + t[1] * (n - pointer - 2))
		if pointer == n - 1:
			break
	print(ans)
	if _ != t1 - 1:
		input()


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 gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
qu = int(input())
for _ in range(qu if True else 1):
	(n, m) = map(int, input().split())
	x = []
	y = []
	di = {}
	z = []
	pairs = []
	for __ in range(m):
		(a, b) = map(int, input().split())
		pairs += [(b, a)]
		z += [a + b]
		if a not in di:
			di[a] = b
		else:
			di[a] = max(di[a], b)
		x += [a]
		y += [b]
	x = sorted(x, reverse=True)
	pairs = sorted(pairs, reverse=True)
	y = sorted(y)
	mv = 0
	for i in di:
		if di[i] == y[-1]:
			mv = max(mv, i)
	(p, q, r) = (0, 0, 0)
	ans = 0
	for i in range(m):
		diff = n - q
		while r < m and diff and (x[r] > pairs[i][0]):
			(p, q, r) = (p + x[r], q + 1, r + 1)
			diff -= 1
		if diff:
			ans = max(ans, p + min(pairs[i]) + pairs[i][0] * (diff - 1))
		else:
			ans = max(ans, p)
		if n == q:
			break
	print(ans)
	if _ != qu - 1:
		input()


from sys import stdin
import math
from bisect import bisect_right
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split(' '))
	a = []
	xs = []
	ans = 0
	for i in range(m):
		(x, y) = map(int, input().split(' '))
		a.append((y, x))
		xs.append(x)
	garbage = input()
	xs.sort(reverse=True)
	a.sort(reverse=True)
	pos = 0
	s = 0
	l = 0
	for i in range(m):
		total = n - l
		y = a[i][0]
		while total and pos < m and (y < xs[pos]):
			total -= 1
			s += xs[pos]
			pos += 1
			l += 1
		if total:
			ans = max(ans, s + min(a[i]) + a[i][0] * (total - 1))
		else:
			ans = max(ans, s)
	print(ans)


import sys, os, io

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

def ri():
	return int(sys.stdin.readline())

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

def ws(s):
	sys.stdout.write(s)
	sys.stdout.write('\n')

def wi(n):
	sys.stdout.write(str(n))
	sys.stdout.write('\n')

def wia(a, sep=' '):
	sys.stdout.write(sep.join([str(x) for x in a]))
	sys.stdout.write('\n')

def solve(n, m, a):
	a = sorted(a, reverse=True)
	pre = [0] * (m + 1)
	for i in range(m):
		pre[i + 1] = pre[i] + a[i][0]
	nm = min(n, m)
	best = pre[nm]
	for i in range(m):
		x = a[i][1]
		lo = -1
		hi = m
		while hi > lo + 1:
			mid = (lo + hi) // 2
			if a[mid][0] >= x:
				lo = mid
			else:
				hi = mid
		if hi >= n:
			continue
		s = pre[hi]
		rem = n - hi
		if i >= hi:
			rem -= 1
			s += a[i][0]
		best = max(best, s + a[i][1] * rem)
	return best

def main():
	for _ in range(ri()):
		(n, m) = ria()
		a = []
		for i in range(m):
			a.append(ria())
		wi(solve(n, m, a))
		rs()

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


from os import path
import sys
from heapq import heappush, heappop, heapify
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

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

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

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

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')
file = 1

def solve():
	for t in range(ii()):
		if t > 0:
			f = si()
		(n, m) = mi()
		a = []
		for i in range(m):
			a.append(li())
		a.sort()
		x = []
		for i in range(m):
			x.append(a[i][0])
		suff = [0] * (m - 1) + [x[-1]]
		for i in range(m - 2, -1, -1):
			suff[i] += suff[i + 1] + x[i]
		if n == 1:
			print(max(x))
			continue

		def f(val):
			if x[-1] < val:
				return m
			l = 0
			r = m - 1
			while l <= r:
				mid = l + (r - l) // 2
				if x[mid] >= val:
					pos = mid
					r = mid - 1
				else:
					l = mid + 1
			return pos
		ans = 0
		for i in range(m):
			x1 = f(a[i][1])
			cnt = 0
			ans1 = 0
			if x[i] < a[i][1]:
				ans1 += x[i]
				cnt += 1
			if x1 < m:
				cnt += m - x1
				if cnt <= n:
					ans1 += suff[x1]
				else:
					cnt -= m - x1
					cnt = n - cnt
					ans1 += suff[m - cnt]
					cnt = n
			ans = max(ans, ans1 + a[i][1] * (n - cnt))
		print(ans)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


import sys, bisect
input = sys.stdin.readline

def solution():
	(n, m) = map(int, input().split())
	flower = [tuple(map(int, input().split())) for _ in range(m)]
	input()
	flower.sort()
	A = [0]
	dp = [0]
	for i in range(m):
		A.append(flower[i][0])
		dp.append(dp[-1] + flower[i][0])
	answer = dp[-1] - dp[-min(n, m) - 1]
	for i in range(m):
		(fa, fb) = flower[i]
		cur = fa + (n - 1) * fb
		answer = max(answer, cur)
		j = bisect.bisect(A, fb)
		alpha_n = m - j + 1
		if alpha_n > n - 1:
			j += abs(alpha_n - (n - 1))
			alpha_n = n - 1
		alpha = dp[-1] - dp[j - 1]
		if fa > fb:
			alpha_n -= 1
			alpha -= fa
		if alpha_n > 0:
			cur -= fb * alpha_n
			answer = max(answer, cur + alpha)
	print(answer)
T = int(input())
for _ in range(T):
	solution()


t = int(input())
for q in range(t):
	(n, m) = list(map(int, input().split()))
	arr = []
	brr = []
	for i in range(m):
		(a, b) = list(map(int, input().split()))
		arr.append([a, 0, i])
		brr.append([b, 1, i])
	if q != t - 1:
		x = input()
	vis = [False for i in range(m)]
	l = arr + brr
	l.sort(reverse=True)
	cnt = 0
	ans = 0
	mex = 0
	for (val, p, ind) in l:
		if p == 0:
			ans += val
			cnt += 1
			vis[ind] = True
			if cnt == n:
				mex = max(mex, ans)
				break
		else:
			now = ans
			if vis[ind] == False:
				now = now + arr[ind][0]
				now = now + (n - cnt - 1) * val
			else:
				now = now + (n - cnt) * val
			mex = max(now, mex)
	print(mex)


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for ttt in range(int(input())):
	if ttt != 0:
		input()
	(n, m) = [int(i) for i in input().split()]
	a = [0] * m
	b = [0] * m
	for i in range(m):
		(ai, bi) = [int(i) for i in input().split()]
		a[i] = ai
		b[i] = bi
	one = [[a[i], i] for i in range(m)]
	two = [[b[i], i] for i in range(m)]
	one.sort()
	two.sort()
	ans = 0
	vis = [0] * m
	cnt = 0
	ans1 = 0
	final = 0
	for i in range(m - 1, -1, -1):
		ans1 = 0
		while cnt < n - 1 and len(one) and (one[-1][0] > two[i][0]):
			ans += one[-1][0]
			cnt += 1
			vis[one[-1][1]] = 1
			one.pop()
		if vis[two[i][1]]:
			ans1 = (n - cnt) * two[i][0]
		else:
			ans1 = (n - cnt - 1) * two[i][0] + a[two[i][1]]
		final = max(final, ans + ans1)
	print(final)


import sys
input = sys.stdin.readline
from bisect import bisect
for test in range(int(input())):
	(n, m) = map(int, input().split())
	(arr, ans) = ([], 0)
	for _ in range(m):
		arr.append(list(map(int, input().split())))
	arr.sort(key=lambda x: x[0])
	prefix = [0] * (m + 1)
	prefix[m - 1] = arr[m - 1][0]
	for i in range(m - 2, -1, -1):
		prefix[i] = prefix[i + 1] + arr[i][0]
	temp = [arr[i][0] for i in range(m)]
	for i in range(m):
		(pos, tempAns) = (bisect(temp, arr[i][1]), 0)
		cnt = m - pos
		if pos != m:
			tempAns = prefix[pos]
		if arr[i][0] < arr[i][1]:
			tempAns += arr[i][0]
			cnt += 1
		if cnt >= n:
			ans = max(ans, prefix[m - n])
		else:
			ans = max(ans, tempAns + (n - cnt) * arr[i][1])
	print(ans)
	try:
		input()
	except:
		pass


import sys
T = int(input())

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]
for t in range(T):
	(n, m) = map(int, input().split())
	pref = [0]
	f = [[0, 0] for x in range(m + 1)]
	f = LLI(m)
	f.sort(reverse=True)
	for i in range(1, m + 1):
		pref.append(f[i - 1][0] + pref[i - 1])
	ans = 0
	mmax = 0
	for i in range(0, m):
		l = 0
		r = m
		use = 0
		while l < r:
			if f[i][1] <= mmax:
				use = r
				break
			mid = (l + r) // 2
			if f[mid][0] >= f[i][1]:
				use = mid + 1
				l = mid + 1
			else:
				r = mid
		mmax = f[i][1]
		if use >= n:
			ans = max(ans, pref[n])
		elif use >= i + 1:
			ans = max(ans, pref[use] + f[i][1] * (n - use))
		else:
			ans = max(ans, pref[use] + f[i][0] + f[i][1] * (n - use - 1))
	print(ans)
	if t != T - 1:
		_ = input()


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd, log
from collections import Counter

def main():
	(n, m) = map(int, input().split())
	a = [0] * m
	l = []
	b = []
	for i in range(m):
		a[i] = tuple(map(int, input().split()))
		l.append(a[i][0])
		b.append(a[i][1])
	if n == 1:
		print(max(l))
		return
	pref = [0] * (m + 1)
	l.sort(reverse=True)
	for i in range(m):
		pref[i + 1] = pref[i] + l[i]
	l.reverse()
	ans = 0
	if n <= m:
		ans = pref[n]
	for i in range(m):
		(el, mx) = a[i]
		ind = bisect_right(l, mx)
		gtr = m - ind
		if gtr <= n and el > mx:
			ans = max(ans, pref[gtr] + mx * (n - gtr))
		elif gtr + 1 <= n and el <= mx:
			ans = max(ans, pref[gtr] + el + mx * (n - 1 - gtr))
	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')
for _ in range(int(input())):
	main()
	input()


import sys
readline = sys.stdin.readline

def solve():
	(N, M) = map(int, readline().split())
	A = [0] * M
	B = [0] * M
	for i in range(M):
		(A[i], B[i]) = map(int, readline().split())
	AI = sorted([(a, i) for (i, a) in enumerate(A)], reverse=True)
	sortedA = [a for (a, i) in AI]
	cum_sortedA = [0] * M
	for i in range(M):
		cum_sortedA[i] = sortedA[i] + (cum_sortedA[i - 1] if i > 0 else 0)
	ans = 0
	for i in range(M):
		value = 0
		b = B[i]
		(l, r) = (-1, M)
		while l + 1 < r:
			m = (l + r) // 2
			if sortedA[m] > b:
				l = m
			else:
				r = m
		if l == -1:
			value = A[i] + b * (N - 1)
		elif N < l + 1:
			value = cum_sortedA[N - 1]
		else:
			value = cum_sortedA[l]
			n = N - (l + 1)
			if A[i] > b:
				value += b * n
			else:
				value += A[i] + b * (n - 1)
		ans = max(ans, value)
	print(ans)
T = int(readline())
for i in range(T):
	solve()
	readline()


import sys, bisect
input = sys.stdin.readline
T = int(input())
for testcase in range(T):
	(n, m) = map(int, input().split())
	ab = [0] * m
	a = [0] * m
	dg = 10 ** 10
	for i in range(m):
		(aa, bb) = map(int, input().split())
		ab[i] = aa * dg + bb
		a[i] = aa
	if testcase != T - 1:
		_ = input()
	a.sort()
	s = [0] * m
	tmp = 0
	for i in range(m - 1, -1, -1):
		tmp += a[i]
		s[i] = tmp
	res = 0
	if n == 1:
		print(a[-1])
		continue
	n -= 1
	for i in range(m):
		(A, B) = divmod(ab[i], dg)
		tmp = A
		k = bisect.bisect_left(a, B)
		if A < B:
			if k == m:
				tmp += n * B
			elif m - k >= n:
				tmp += s[m - n]
			else:
				tmp += s[k] + (n - (m - k)) * B
		elif a[k] == A:
			k += 1
			if k == m:
				tmp += n * B
			elif m - k >= n:
				tmp += s[m - n]
			else:
				tmp += s[k] + (n - (m - k)) * B
		else:
			p = bisect.bisect_left(a, A)
			if m - 1 - p >= n:
				tmp += s[m - n]
			elif m - k - 1 >= n:
				tmp += s[m - (n + 1)] - A
			else:
				tmp += s[k] - A + (n - (m - k - 1)) * B
		res = max(res, tmp)
	print(res)


from sys import stdin

def solve():
	(n, m) = [int(i) for i in stdin.readline().split()]
	s = []
	for i in range(m):
		s.append(tuple((int(j) for j in stdin.readline().split())))
	s.sort(reverse=True)
	g = [0] * (m + 1)
	for i in range(1, m + 1):
		g[i] = g[i - 1] + s[i - 1][0]
	ans = 0
	for i in range(m):
		l = -1
		r = m
		while r - l > 1:
			mid = (l + r) // 2
			if s[mid][0] < s[i][1]:
				r = mid
			else:
				l = mid
		r = min(r, n)
		ann = 0
		ann += g[r]
		other = n - r
		if r <= i and r < n:
			ann += s[i][0]
			other -= 1
		ann += s[i][1] * other
		ans = max(ans, ann)
	print(ans)

def stupid():
	(n, m) = map(int, stdin.readline().split())
	flowers = []
	for i in range(m):
		(a, b) = map(int, stdin.readline().split())
		flowers.append((a, b))
	flowers.sort(reverse=True)
	p = [0] * (m + 1)
	p[0] = 0
	for i in range(1, m + 1):
		p[i] = p[i - 1] + flowers[i - 1][0]
	best = -1
	for i in range(m):
		(ax, bx) = flowers[i]
		(l, r) = (-1, m)
		while r - l > 1:
			mid = (r + l) // 2
			if flowers[mid][0] < flowers[i][1]:
				r = mid
			else:
				l = mid
		ind = min(r, n)
		res = 0
		res += p[ind]
		other = n - ind
		if ind <= i and ind < n:
			res += ax
			other -= 1
		res += bx * other
		best = max(best, res)
	print(best)
q = int(stdin.readline())
for space in range(q):
	stupid()
	if space < q - 1:
		stdin.readline()


import sys, heapq
input = sys.stdin.readline
for _ in range(int(input())):
	if _ != 0:
		s = input()
	(n, m) = map(int, input().split())
	flower = []
	for i in range(m):
		(a, b) = map(int, input().split())
		flower.append((b, a))
	flower.sort()
	S = 0
	N = 0
	ans = -1
	que = []
	if n == 1:
		ans = max((flower[i][1] for i in range(m)))
		print(ans)
		continue
	for i in range(m):
		(b, a) = flower[i]
		while que and b > que[0]:
			A = heapq.heappop(que)
			S -= A
			N -= 1
		temp = b * (n - 1 - N) + a + S
		ans = max(temp, ans)
		if N == n - 1:
			if que[0] < a:
				S -= que[0]
				heapq.heappop(que)
				S += a
				heapq.heappush(que, a)
		else:
			heapq.heappush(que, a)
			S += a
			N += 1
	print(ans)


import sys
input = sys.stdin.readline
import bisect
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ab = [list(map(int, input().split())) for i in range(m)]
	ab.sort()
	cuma = [0]
	a = [0]
	for i in range(m):
		now = ab[i][0]
		a.append(now)
		cuma.append(cuma[-1] + now)
	ans = 0
	for i in range(m):
		(x, b) = ab[i]
		ind = bisect.bisect_right(a, b)
		if m + 1 - ind >= n:
			count = cuma[-1] - cuma[-1 - n]
			left = 0
		else:
			count = cuma[-1] - cuma[ind - 1]
			left = n - (m + 1 - ind)
		if x < b:
			count += x
			left -= 1
		count += left * b
		ans = max(ans, count)
	print(ans)
	if _ != t - 1:
		s = input()


from math import *
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = []
	b = []
	cost = []
	pc = []
	vis = [0] * m
	ans = -1
	for i in range(m):
		(ai, bi) = map(int, input().split())
		pc.append((ai, bi))
		cost.append((ai, bi, i, -1))
		cost.append((bi, ai, i, -2))
	if _ < t - 1:
		input()
	cost.sort(reverse=True)
	val = 0
	bt = 0
	for i in range(len(cost)):
		if bt >= n:
			break
		if cost[i][-1] == -1:
			ans = max(ans, val + cost[i][0] + max(0, n - bt - 1) * cost[i][1])
			val += cost[i][0]
			vis[cost[i][2]] = 1
			bt += 1
		elif cost[i][-1] == -2 and vis[cost[i][2]] == 1:
			ans = max(ans, val + (n - bt) * cost[i][0])
		else:
			ans = max(ans, val + cost[i][1] + (n - bt - 1) * cost[i][0])
	print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
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=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 SegmentTree1:

	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)
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(11)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

	def find(self, x):
		if self.par[x] != x:
			self.par[x] = self.find(self.par[x])
		return self.par[x]

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

	def size(self, x):
		return self.sz[self.find(x)]

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

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

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = -1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
t = 1
t = int(input())
for _ in range(t):
	if _:
		input()
	(n, m) = map(int, input().split())
	(a, arr, post) = ([], [], [0] * m)
	for i in range(m):
		(x, y) = map(int, input().split())
		a.append(x)
		arr.append([x, y])
	a.sort()
	arr.sort()
	post[-1] = a[-1]
	for i in range(m - 2, -1, -1):
		post[i] = post[i + 1] + a[i]
	ans = 0
	if n <= m:
		ans = post[m - n]
	for i in range(m):
		ind = binarySearch(a, m, arr[i][1])
		nc = n
		res = 0
		if ind < m:
			d = min(m - ind, nc)
			res += post[m - d]
			nc -= d
		if nc and arr[i][0] <= arr[i][1]:
			nc -= 1
			res += arr[i][0]
		res += arr[i][1] * nc
		ans = max(ans, res)
	print(ans)


import time, math as mt, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

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

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return
mod = 10 ** 9 + 7

def solve(i):
	if i != 0:
		s = input()
	(n, m) = IP()
	(a, b, ao) = ([], [], [])
	for i in range(m):
		(aa, bb) = IP()
		ao.append(aa)
		a.append(aa)
		b.append(bb)
	a.sort()
	pref = [0] * m
	pref[0] = a[0]
	for i in range(1, m):
		pref[i] = pref[i - 1] + a[i]
	ans = -1 * 1000000000000000.0
	x = 0
	for i in range(m):
		pos = bisect.bisect_right(a, b[i])
		cnt = m - pos
		if cnt >= n:
			if m - n - 1 >= 0:
				x = pref[m - n - 1]
			else:
				x = 0
			ans = max(ans, pref[m - 1] - x)
		elif cnt == 0:
			ans = max(ans, b[i] * (n - 1) + ao[i])
		elif cnt == m:
			ans = max(ans, b[i] * (n - m) + pref[m - 1])
		else:
			a_to_take = ao[i]
			if a_to_take >= b[i]:
				cost = b[i] * (n - cnt) + (pref[m - 1] - pref[pos - 1])
			else:
				cost = b[i] * (n - cnt - 1) + (pref[m - 1] - pref[pos - 1]) + a_to_take
			ans = max(ans, cost)
	P(ans)
t = II()
for i in range(t):
	solve(i)


import bisect
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = [list(map(int, input().split())) for _ in range(m)]
	arr_a = [arr[i][0] for i in range(m)]
	arr_a = sorted(arr_a)
	acum = [0]
	for i in range(m):
		acum.append(acum[-1] + arr_a[i])
	ans = 0
	for (a, b) in arr:
		pos = bisect.bisect_left(arr_a, b)
		cnt = min(m - pos, n)
		tmp = acum[m] - acum[m - cnt] + b * (n - cnt)
		if a < b and n - cnt != 0:
			tmp += a
			tmp -= b
		ans = max(ans, tmp)
	print(ans)
	_ = input()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	if _ > 0:
		input()
	(n, m) = map(int, input().split())
	flowers = []
	for i in range(m):
		(a, b) = map(int, input().split())
		flowers.append((a, b))
	flowers.sort(reverse=True)
	pref_sums = [0] * (m + 1)
	for i in range(m):
		pref_sums[i + 1] = pref_sums[i] + flowers[i][0]
	ans = 0
	for k in range(m):
		l = -1
		r = m
		a = flowers[k][0]
		b = flowers[k][1]
		while r - l > 1:
			mid = (r + l) // 2
			if flowers[mid][0] <= b:
				r = mid
			else:
				l = mid
		l = min(l, n - 1)
		if l >= k:
			ans = max(ans, pref_sums[l + 1] + b * (n - l - 1))
		else:
			l = min(l, n - 2)
			ans = max(ans, pref_sums[l + 1] + b * (n - l - 1 - 1) + a)
	print(ans)


import math
import collections
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2 ** 20)
t = 1
t = int(stdin.readline())
for _ in range(t):
	(n, m) = list(map(int, stdin.readline().rstrip().split()))
	a = []
	b = []
	d = {}
	db = {}
	for j in range(m):
		(t1, t2) = list(map(int, stdin.readline().rstrip().split()))
		a.append(t1)
		b.append((t2, j))
		d[j] = t1
		db[j] = t2
	a.sort()
	b.sort(reverse=True)
	pre = [0] * (m - 1) + [a[-1]]
	for i in range(m - 2, -1, -1):
		pre[i] = pre[i + 1] + a[i]
	pre = pre[::-1]
	bal = n
	cnt = -1
	for i in b:
		tmp = i[0]
		t2 = bsl(a, tmp)
		t2 = m - t2
		if t2 >= n:
			ans = pre[n - 1]
		elif t2 == 0:
			ans = d[i[1]] + (n - 1) * tmp
		else:
			ans = pre[t2 - 1] + d[i[1]] + (n - t2 - 1) * tmp
			if d[i[1]] >= tmp:
				ans -= d[i[1]] - tmp
		cnt = max(cnt, ans)
	print(cnt)
	new = stdin.readline()


def main():
	import bisect
	import sys
	input = sys.stdin.buffer.readline
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		ab = [tuple(map(int, input().split())) for i in range(m)]
		B = 0
		ans = 0
		s = set()
		ab.sort(key=lambda x: x[0])
		A = [0] * m
		SA = [0] * (m + 1)
		for (i, a) in enumerate(ab):
			A[i] = a[0]
			SA[i + 1] = SA[i] + a[0]
		tmp = 0
		if n > 0:
			for (i, AB) in enumerate(ab):
				(a, b) = AB
				id = bisect.bisect_right(A, b)
				tmp = SA[m] - SA[max(id, m - n)]
				L = n - (m - max(m - n, id))
				if a > b:
					ans = max(ans, tmp + b * L)
				else:
					ans = max(ans, tmp + b * (L - 1) + a)
		print(ans)
		if _ < t - 1:
			__ = input()
main()


import sys
input = sys.stdin.readline
t = int(input())
for trial in range(t):
	(n, m) = map(int, input().split())
	both = []
	for i in range(m):
		(a1, b1) = map(int, input().split())
		both.append([a1, b1])
	if trial < t - 1:
		input()
	ans = 0
	sort_by_a = sorted(both, key=lambda x: (x[0], x[1]), reverse=True)
	sort_by_b = sorted(both, key=lambda x: (x[1], x[0]), reverse=True)
	sum_of_a = 0
	a_index = 0
	max_b = 0
	for i in range(m):
		while a_index < m and sort_by_a[a_index][0] > sort_by_b[i][1]:
			sum_of_a += sort_by_a[a_index][0]
			max_b = max(sort_by_a[a_index][1], max_b)
			a_index += 1
			if a_index == n or a_index == m:
				break
		if a_index == n or sort_by_b[i][1] < max_b:
			ans = max(sum_of_a, ans)
			break
		if sort_by_b[i][0] > sort_by_b[i][1]:
			ans = max(ans, sum_of_a + (n - a_index) * sort_by_b[i][1])
		else:
			ans = max(ans, sum_of_a + (n - a_index - 1) * sort_by_b[i][1] + sort_by_b[i][0])
	print(ans)


import sys
from itertools import accumulate
from bisect import bisect_right

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')
INF = 10 ** 19
MOD = 10 ** 9 + 7
T = INT()
for t in range(T):
	(N, M) = MAP()
	A = [0] * M
	B = [0] * M
	for i in range(M):
		(A[i], B[i]) = MAP()
	A2 = sorted(A)
	acc = list(accumulate(A2[::-1]))[::-1] + [0]
	A2.append(INF)
	ans = 0
	for i in range(M):
		j = bisect_right(A2, B[i])
		cur = 0
		cnt = M - j
		if cnt > N:
			j = M - N
			cnt = N
		if A2[j] > A[i]:
			cur += A[i]
			if cnt == N:
				j += 1
			else:
				cnt += 1
		cur += acc[j] + (N - cnt) * B[i]
		ans = max(ans, cur)
	print(ans)
	if t != T - 1:
		input()


from sys import stdin, stdout

def bsearch(ar, x):
	low = 0
	high = len(ar) - 1
	ans = -1
	while low <= high:
		mid = (low + high) // 2
		if ar[mid][0] >= x:
			ans = mid
			low = mid + 1
		else:
			high = mid - 1
	return ans
t = int(stdin.readline())
for test in range(t):
	(n, m) = map(int, stdin.readline().split())
	la = []
	lb = []
	templa = []
	templb = []
	for i in range(m):
		(a, b) = map(int, stdin.readline().split())
		la.append([a, i])
		templa.append(a)
		lb.append(b)
		templb.append(b)
	la.sort(reverse=True)
	pre = [la[0][0]]
	for i in range(1, m):
		pre.append(pre[-1] + la[i][0])
	sm = 0
	mx = 0
	mxb = 0
	for i in range(m):
		b = lb[i]
		idx = min(bsearch(la, b), n - 1)
		if idx != -1:
			sm += pre[idx]
			if templa[i] > b:
				taken = 0
			else:
				taken = 1
			sm = pre[idx] + b * (n - idx - 1 - taken) + templa[i] * taken
		else:
			sm = templa[i] + templb[i] * (n - 1)
		mx = max(sm, mx)
	stdout.write(f'{mx}\n')
	if test != t - 1:
		stdin.readline()


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		if p == t - 1:
			solve(False)
			continue
		solve(True)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def bfs(g, st):
	visited = [0] * len(g)
	visited[st] = 1
	queue = []
	queue.append(st)
	new = []
	while len(queue) != 0:
		s = queue.pop()
		new.append(s)
		for i in g[s]:
			if visited[i] == 0:
				visited[i] = visited[s] + 1
				queue.append(i)
	return visited

def solve(bakchodi):
	(n, m) = sep()
	new = []
	arr = []
	brr = []
	for i in range(m):
		(a, b) = sep()
		arr.append(a)
		brr.append(b)
		new.append([a, i, 0])
		new.append([b, i, 1])
	if bakchodi:
		s = inp()
	new = sorted(new)[::-1]
	used = [False] * m
	i = 0
	ans = 0
	ans1 = 0
	while n != 0 and i < len(new):
		if new[i][2] == 0:
			ans += new[i][0]
			used[new[i][1]] = True
			n -= 1
			i += 1
			if n == 0:
				ans = max(ans, ans1)
		elif used[new[i][1]]:
			ans += n * new[i][0]
			ans = max(ans, ans1)
			print(ans)
			return
		else:
			ans1 = max(ans1, ans + arr[new[i][1]] + (n - 1) * new[i][0])
			i += 1
	print(max(ans, ans1))
testcase(int(inp()))


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

class flo:

	def __init__(self, a, b, c):
		self.po = int(a)
		self.ty = b
		self.ind = c

	def __lt__(self, other):
		return self.po < other.po

	def __str__(self):
		return f'{self.po} {self.ty} {self.ind}'
cas = int(input())
for ca in range(cas):
	(n, m) = map(int, input().split())
	flowers = []
	a_used = [0] * m
	powe = []
	for i in range(m):
		(a1, b1) = input().split()
		flowers.append(flo(a1, 'a', i))
		flowers.append(flo(b1, 'b', i))
		powe.append((int(a1), int(b1)))
	flowers.sort(reverse=True)
	maxi = ans = 0
	for i in range(len(flowers)):
		x = flowers[i]
		if x.ty == 'a':
			ans += x.po
			a_used[x.ind] = 1
			n -= 1
		elif a_used[x.ind] == 1:
			ans1 = ans + x.po * n
			maxi = max(maxi, ans1)
		else:
			ans1 = ans + (n - 1) * x.po + powe[x.ind][0]
			maxi = max(maxi, ans1)
		if not n:
			maxi = max(ans, maxi)
			break
	print(maxi)
	if ca != cas - 1:
		input()


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

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

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def bfs(adj):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

def dfs(u, top, adj, vis):
	vis[u] = 1
	for (v, d) in adj[u]:
		if vis[v] == 2 or d == 0:
			continue
		if vis[v] == 1:
			return 'No'
		if dfs(v, top, adj, vis) == 'No':
			return 'No'
	vis[u] = 2
	top.append(u)
from bisect import bisect_right

def solution(a, b, both, n, m):
	max_opt = -1
	a.sort(reverse=True)
	a = [-x for x in a]
	prefix = [0]
	for x in a:
		prefix.append(prefix[-1] - x)
	for (l, r) in both:
		i = bisect_right(a, -r)
		if i >= n:
			opt = prefix[n]
		else:
			opt = prefix[i]
			if l >= r:
				opt += (n - i) * r
			else:
				opt += (n - i - 1) * r + l
		max_opt = max(max_opt, opt)
	return max_opt

def main():
	T = 1
	T = ri()
	for i in range(T):
		(n, m) = ria()
		(a, b) = ([], [])
		both = []
		for _ in range(m):
			(l, r) = ria()
			a.append(l)
			b.append(r)
			both.append((l, r))
		x = solution(a, b, both, n, m)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
		f.readline()
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


def binary_search(arr, low, high, x):
	mid = (high + low) // 2
	if arr[mid] >= x and (mid + 1 == len(arr) or arr[mid + 1] < x):
		return mid
	elif arr[mid] > x:
		return binary_search(arr, low, mid - 1, x)
	else:
		return binary_search(arr, mid + 1, high, x)

def main(r):
	if r > 0:
		ln = input()
	(n, m) = map(int, input().split())
	lst = []
	max_prev = 0
	a_prev = []
	a_prev_step_sm = [0]
	for i in range(m):
		(a, b) = map(int, input().split())
		lst.append(tuple([a, b]))
	lst = sorted(lst, reverse=True)
	for i in lst:
		a_prev.append(i[0])
		a_prev_step_sm.append(a_prev_step_sm[-1] + i[0])
	k = len(a_prev) - 1
	max_sm = 0
	if len(a_prev_step_sm) - 1 >= n:
		max_sm = a_prev_step_sm[n]
	for i in range(len(lst)):
		if lst[i][1] > max_prev:
			max_prev = lst[i][1]
			while k >= 0 and lst[i][1] >= a_prev[k]:
				k -= 1
			if k >= i:
				if k + 1 >= n:
					pass
				else:
					sm = a_prev_step_sm[k + 1] + (n - k - 1) * max_prev
					max_sm = max(sm, max_sm)
			elif k + 2 >= n:
				pass
			else:
				sm = a_prev_step_sm[k + 1] + a_prev[i] + (n - k - 2) * max_prev
				max_sm = max(sm, max_sm)
	print(max_sm)
t = int(input())
for i in range(t):
	main(i)


from __future__ import print_function
from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()
for _ in range(t):
	(n, m) = gil()
	p = []
	for _ in range(m):
		p.append(gil())
	a = [p[i][0] for i in range(m)]
	a.sort(reverse=True)

	def getIdx(bi):
		(l, r) = (0, m - 1)
		idx = 0
		while l <= r:
			mid = (l + r) // 2
			if a[mid] > bi:
				l = mid + 1
				idx = mid
			else:
				r = mid - 1
		return idx
	pre = a[:]
	for i in range(1, m):
		pre[i] += pre[i - 1]
	idx = {}
	for i in range(m):
		idx[a[i]] = i
	ans = pre[min(m - 1, n - 1)]
	if n != 1:
		for (ai, bi) in p:
			if bi > a[0]:
				ans = max(ans, ai + bi * (n - 1))
				continue
			j = getIdx(bi)
			if idx[ai] <= min(j, n - 2):
				if j > n - 1:
					ans = max(ans, pre[n - 1])
				else:
					ans = max(ans, pre[j] + (n - j - 1) * bi)
			else:
				j = min(j, n - 2)
				ans = max(ans, ai + pre[j] + (n - j - 2) * bi)
	print(ans)
	g()


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations

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

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

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for x in input().split()]

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

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

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

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

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

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def bo(i):
	return ord(i) - ord('a')
t = fi()
while t > 0:
	t -= 1
	(n, m) = mi()
	a = []
	b = []
	for i in range(m):
		p = li()
		a.append(p[0])
		b.append([p[0], p[1]])
	if t > 0:
		input()
	a.sort()
	tot = sum(a)
	pre = [a[0] for i in range(m)]
	for i in range(1, m):
		pre[i] = pre[i - 1] + a[i]
	ans = sum(a[-min(n, m):])
	pre.append(0)
	for i in range(m):
		p = bisect_left(a, b[i][1])
		q = bisect_left(a, b[i][0])
		l = m - p
		if l > n:
			continue
		if q >= p:
			u = tot - pre[p - 1] + b[i][1] * (n - l)
		else:
			u = tot - pre[p - 1] + b[i][0] + b[i][1] * (n - l - 1)
		ans = max(u, ans)
	print(ans)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
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
avl = AvlTree()

class SegmentTree1:

	def __init__(self, data, default='z', 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)

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 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
tot = int(input())
for ik in range(tot):
	if ik != 0:
		s = input()
	(n, b) = map(int, input().split())
	l = []
	l1 = []
	for i in range(b):
		(f, g) = map(int, input().split())
		l.append((f, g))
		l1.append((f, g))
	l.sort(reverse=True, key=lambda x: x[1])
	l1.sort(reverse=True)
	b = len(l)
	t = 0
	su = 0
	f = 1
	ans = -1
	ind = set()
	cou = 0
	for i in range(b):
		rty = 0
		rt = 0
		for j in range(t, b):
			if cou >= n:
				break
			elif l1[j][0] >= l[i][1]:
				su += l1[j][0]
				ind.add(l1[j])
				cou += 1
			else:
				break
		t = j
		if l1[t][0] >= l[i][1]:
			t += 1
		if l[i] in ind:
			rt = 1
		if cou + (1 - rt) >= n:
			rty = su
			if cou == n - 1 and rt == 0:
				rty += l[i][0]
		else:
			rty = su + (n - cou - (1 - rt)) * l[i][1] + (1 - rt) * l[i][0]
		ans = max(ans, rty)
	if f == 1:
		print(ans)


import sys
input = sys.stdin.readline
import bisect
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	initial = []
	combo = []
	flowers = []
	for _ in range(m):
		(a, b) = map(int, input().split())
		initial.append(a)
		flowers.append((a, b))
	initial.sort()
	if n <= m:
		ans = sum(initial[-n:])
	else:
		ans = 0
	total = sum(initial)
	cumsum = [0]
	for item in initial:
		cumsum.append(cumsum[-1] + item)
	for (a, b) in flowers:
		ret = a + (n - 1) * b
		index = bisect.bisect_right(initial, b)
		a_index = bisect.bisect_left(initial, a)
		cnt = m - index
		if cnt > n:
			continue
		if a_index >= index:
			val = total - cumsum[index] - a
			ret = ret + val - (cnt - 1) * b
		else:
			val = total - cumsum[index]
			ret = ret + val - cnt * b
		ans = max(ans, ret)
	print(ans)
	blank = input()


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
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')

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())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [(ch, len(list(g))) for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None
t = N()
for k in range(t):
	(n, m) = RL()
	res = []
	A = []
	for i in range(m):
		(a, b) = RL()
		res.append((b, a))
		A.append(a)
	res.sort(reverse=True)
	A.sort(reverse=True)
	pre = [0]
	for a in A:
		pre.append(pre[-1] + a)
	j = 0
	ans = 0
	for i in range(m):
		b = res[i][0]
		tmp = res[i][1] + (n - 1) * b
		while j < m and A[j] > b:
			j += 1
		if res[i][1] > b:
			if j >= n:
				tmp += pre[n] - n * b
				tmp -= res[i][1] - b
			else:
				tmp += pre[j] - j * b
				tmp -= res[i][1] - b
		elif j >= n - 1:
			tmp += pre[n - 1] - (n - 1) * b
		else:
			tmp += pre[j] - j * b
		ans = max(ans, tmp)
	print(ans)
	if k < t - 1:
		tmp = sys.stdin.readline()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def get_str():
	return input().decode().strip()

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

def oint():
	return int(input())

def binary_search(bb):
	lo = 0
	hi = m
	while lo < hi:
		mid = (lo + hi) // 2
		if bb < a[ai[mid]]:
			lo = mid + 1
		else:
			hi = mid
	return lo - 1
t = oint()
for _ in range(t):
	(n, m) = rint()
	a = []
	b = []
	sum_ = 0
	for i in range(m):
		(aa, bb) = rint()
		a.append(aa)
		b.append(bb)
	ai = [i for i in range(m)]
	ai.sort(key=lambda i: -a[i])
	aps = [a[ai[0]]]
	for i in range(1, m):
		aps.append(aps[-1] + a[ai[i]])
	max_sum = -1
	for i in range(m):
		j = binary_search(b[i])
		if j + 1 >= n:
			sum_ = aps[n - 1]
		else:
			sum_ = a[i] + b[i] * (n - 1 - (j + 1))
			if j >= 0:
				sum_ += aps[j]
				if a[ai[j]] <= a[i]:
					sum_ += b[i] - a[i]
		max_sum = max(max_sum, sum_)
	print(max_sum)
	input()


from sys import stdin, stdout

def input():
	return stdin.readline().strip()
import bisect

def choose(n, pA, cA, A, repeat_a, repeat_b):
	n -= 1
	ret = repeat_a
	i = bisect.bisect_left(A, -repeat_b)
	if i == len(A) or -A[i] < repeat_a:
		n += 1
		i = min(i, n)
		return -pA[i] + (n - i) * repeat_b
	else:
		i = min(i, n)
		return -pA[i] + (n - i) * repeat_b + repeat_a

def ans(n, flowers):
	ret = float('-inf')
	A = [-a for (a, b) in flowers]
	A = sorted(A)
	pA = [0]
	for a in A:
		pA += [pA[-1] + a]
	for i in range(len(flowers)):
		ret = max(ret, choose(n, pA, None, A, flowers[i][0], flowers[i][1]))
	return ret
T = int(input())
for t in range(T):
	if t > 0:
		input()
	(n, m) = input().split(' ')
	n = int(n)
	m = int(m)
	flowers = []
	for _ in range(m):
		(a, b) = input().split(' ')
		a = int(a)
		b = int(b)
		flowers += [(a, b)]
	print(ans(n, flowers))


import bisect

def cin():
	return map(int, input().split())
T = int(input())
for t in range(T):
	(n, m) = cin()
	(a, b) = ([], [])
	for i in range(m):
		(ai, bi) = cin()
		a.append(ai)
		b.append((ai, bi))
	a.sort()
	c = [0]
	for i in range(m):
		c.append(a[i] + c[-1])
	ans = 0
	for (ai, bi) in b:
		i = bisect.bisect_left(a, bi)
		cnt = min(m - i, n)
		curr = c[m] - c[m - cnt] + bi * (n - cnt)
		if ai < bi and n - cnt != 0:
			curr += ai
			curr -= bi
		ans = max(ans, curr)
	print(ans)
	if t != T - 1:
		_ = input()


import sys

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

def print_list(l):
	print(' '.join(map(str, l)))
import bisect as bs
import math
input = sys.stdin.readline
N = int(input())
for _ in range(N):
	(n, m) = read_list()
	a = [0] * m
	b = [[0, i] for i in range(m)]
	for i in range(m):
		(a[i], b[i][0]) = read_list()
	input()
	sa = sorted(a)
	sb = sorted(b)
	tt = [0]
	for i in sa[::-1]:
		tt.append(tt[-1] + i)
	ma = 0
	res = 0
	for fb in sb[::-1]:
		ind = fb[1]
		vb = fb[0]
		if a[ind] <= ma:
			break
		ma = min(ma, a[ind])
		k = bs.bisect_left(sa, vb)
		if n <= m - k:
			tmp = tt[n]
		else:
			tmp = tt[m - k]
			if a[ind] < vb:
				tmp += a[ind]
				tmp += (n - (m - k) - 1) * vb
			else:
				tmp += (n - (m - k)) * vb
		res = max(res, tmp)
	print(res)


import sys
from bisect import bisect_left
input = sys.stdin.buffer.readline
T = int(input())
for t in range(T):
	if t > 0:
		input()
	(n, m) = map(int, input().split())
	ls = []
	for _ in range(m):
		(a, b) = map(int, input().split())
		ls.append((a, b))
	(al, psm) = ([-a for (a, _) in ls], [0] * m)
	al.sort()
	for i in range(m):
		psm[i] += (psm[i - 1] if i > 0 else 0) - al[i]
	maxhp = 0
	for (a, b) in ls:
		cc = 0
		p = min(bisect_left(al, -b), n)
		if p > 0:
			cc += psm[p - 1]
		cc += (n - p) * b
		if p < n and a < b:
			cc += a - b
		maxhp = max(maxhp, cc)
	print(maxhp)


from sys import stdin
TT = int(stdin.readline())
for loop in range(TT):
	(n, m) = map(int, stdin.readline().split())
	ba = []
	alis = []
	for i in range(m):
		(a, b) = map(int, stdin.readline().split())
		ba.append((b, a))
		alis.append(a)
	alis.sort()
	alis.reverse()
	ss = [0]
	for i in range(m):
		ss.append(ss[-1] + alis[i])
	ans = 0
	for i in range(m):
		(b, a) = ba[i]
		l = -1
		r = m
		while r - l != 1:
			mid = (l + r) // 2
			if alis[mid] >= b:
				l = mid
			else:
				r = mid
		if l == -1:
			ans = max(ans, a + b * (n - 1))
			continue
		if alis[l] > a:
			if l + 1 + 1 <= n:
				ans = max(ans, a + ss[l + 1] + b * (n - (l + 2)))
			else:
				ans = max(ans, a + ss[n - 1])
		elif l + 1 <= n:
			ans = max(ans, ss[l + 1] + b * (n - (l + 1)))
		else:
			ans = max(ans, ss[n])
	print(ans)
	if loop != TT - 1:
		stdin.readline()


import sys
input = sys.stdin.readline

def bs(a, x):
	(l, r) = (-1, len(a))
	while r - l > 1:
		md = (r + l) // 2
		if x >= a[md]:
			l = md
		else:
			r = md
	return r
for _ in range(int(input())):
	if _ > 0:
		ZZZ = input()
	(n, m) = map(int, input().split())
	p = [list(map(int, input().split())) for _ in range(m)]
	a = sorted([x[0] for x in p])
	S = [0] * m
	S[m - 1] = a[m - 1]
	for i in range(m - 2, -1, -1):
		S[i] = S[i + 1] + a[i]
	maxx = 0
	for (x, y) in p:
		idx = bs(a, y)
		nums = m - idx
		s = 0
		if n > nums:
			remain = n - nums
			if idx < m:
				s += S[idx]
				if x >= a[idx]:
					s += remain * y
				else:
					s += x + (remain - 1) * y
			else:
				s += x + (remain - 1) * y
		else:
			s += S[-n]
		maxx = max(maxx, s)
	print(maxx)


import bisect
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	li = []
	for i in range(m):
		(a, b) = list(map(int, input().split()))
		li.append([a, b])
	li.sort(key=lambda x: x[0])
	li[-1].append(li[-1][0])
	for i in range(m - 2, -1, -1):
		li[i].append(li[i + 1][2] + li[i][0])
	ans = 0
	for ele in li:
		c = m - bisect.bisect_right(li, [ele[1], 10 ** 10, 10 ** 10])
		temp = ele[0]
		rem = n - 1
		if rem > 0 and c > rem and (c > 0):
			temp += li[-1 * rem][2]
			if ele[0] >= li[-1 * rem][0]:
				temp += li[-1 * rem - 1][0]
				temp -= ele[0]
			rem = 0
		if rem > 0 and c == rem and (c > 0):
			temp += li[-1 * rem][2]
			if ele[0] >= li[-1 * rem][0]:
				temp -= ele[0]
				rem = 1
			else:
				rem = 0
		if rem > 0 and c < rem and (c > 0):
			rem -= c
			temp += li[-1 * c][2]
			if ele[0] >= li[-1 * c][0]:
				temp -= ele[0]
				rem += 1
		if rem > 0:
			temp += ele[1] * rem
		if temp > ans:
			ans = temp
	print(ans)
	if _ < t - 1:
		input()


import sys
input = sys.stdin.readline
for f in range(int(input())):
	(n, m) = map(int, input().split())
	a = [0] * m
	b = [0] * m
	acop = [0] * m
	bcop = [0] * m
	for i in range(m):
		(a[i], b[i]) = map(int, input().split())
		acop[i] = a[i]
		bcop[i] = [b[i], i]
	acop.sort(reverse=True)
	bcop.sort(reverse=True)
	mx = 0
	i = 0
	su = 0
	for j in range(m):
		bi = bcop[j][0]
		ii = bcop[j][1]
		ai = a[ii]
		while i < m and acop[i] > bi:
			su += acop[i]
			i += 1
		maxi = ai
		if i < n:
			maxi += su
			if i + 1 < n:
				maxi += (n - i - 1) * bi
			if ai > bi:
				maxi += bi
				maxi -= ai
			mx = max(maxi, mx)
	if n <= m:
		sun = 0
		for i in range(n):
			sun += acop[i]
		mx = max(mx, sun)
	print(mx)
	blank = input()


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	if _:
		input()
	(n, m) = map(int, input().split())
	a = []
	b = []
	for i in range(m):
		(v1, v2) = map(int, input().split())
		a.append(v1)
		b.append((v2, v1))
	a.sort(reverse=True)
	b.sort(reverse=True)
	c = 0
	l = 0
	summ = 0
	act = 0
	for i in range(m):
		tot = n - l
		while tot and c < m and (a[c] > b[i][0]):
			tot -= 1
			l += 1
			summ += a[c]
			c += 1
		if tot:
			act = max(act, summ + min(b[i]) + b[i][0] * (tot - 1))
		else:
			act = max(act, summ)
	print(act)


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def output(*args):
	sys.stdout.buffer.write(('\n'.join(map(str, args)) + '\n').encode('utf-8'))

def main():
	t = int(input())
	ans_a = [''] * t
	for ti in range(t):
		if ti:
			input()
		(n, m) = map(int, input().split())
		a = [10 ** 9 + 100] * (m + 1)
		acc = [0] * (m + 1)
		b = [0] * (m + 1)
		for (i, (ai, bi)) in enumerate(sorted([list(map(int, input().split())) for _ in range(m)], reverse=True), start=1):
			acc[i] = a[i] = ai
			b[i] = bi
		for i in range(1, m):
			acc[i + 1] += acc[i]
		ans = acc[min(n, m)] + max(0, n - m) * max(b)
		l = m
		for i in sorted(range(1, m + 1), key=lambda i: b[i]):
			while a[l] <= b[i]:
				l -= 1
			if l >= n:
				continue
			if a[l] > a[i]:
				ans = max(ans, acc[l] + a[i] + b[i] * (n - l - 1))
			else:
				ans = max(ans, acc[l] + b[i] * (n - l))
		ans_a[ti] = str(ans)
	output(*ans_a)
main()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
from bisect import bisect_left

def solve():
	(n, m) = map(int, input().split())
	a = []
	for i in range(m):
		(ai, bi) = map(int, input().split())
		a.append((ai, bi))
	a.sort(key=lambda x: x[0])
	b = []
	presum = [0]
	for i in range(m):
		b.append(a[i][1])
		a[i] = a[i][0]
		presum.append(presum[-1] + a[i])
	ma = 0
	for i in range(m):
		s = a[i]
		ind = bisect_left(a, b[i])
		if m - ind > n - 1:
			s += presum[m] - presum[m - n + 1]
		else:
			s += presum[m] - presum[ind]
			s += b[i] * (n - 1 - (m - ind))
		if ind <= i:
			if m - ind <= n - 1:
				s -= a[i]
				s += b[i]
			else:
				s -= a[i]
				s += a[m - n]
		if s > ma:
			ma = s
	print(ma)

def main():
	t = int(input())
	for i in range(t):
		solve()
		if i != t - 1:
			input()
main()


from sys import stdin
t = int(input())
for t in range(t, 0, -1):
	(n, m) = map(int, stdin.readline().split())
	first = []
	pair = []
	for _ in range(m):
		(a, b) = map(int, stdin.readline().split())
		first.append(a)
		pair.append([b, a])
	pair = sorted(pair)[::-1]
	first = sorted(first)[::-1]
	MAX = sum(first[:n])
	i = 0
	SUM = 0
	for (b, a) in pair:
		for i in range(i, m):
			if first[i] <= b:
				break
			SUM += first[i]
			i += 1
		if n < i:
			break
		if a > b:
			MAX = max(MAX, SUM + (n - i) * b)
		else:
			if n < i + 1:
				break
			MAX = max(MAX, SUM + (n - i - 1) * b + a)
	print(MAX)
	if t != 1:
		input()


import sys
from bisect import bisect_left
input = sys.stdin.readline
t = int(input())
for zz in range(t):
	(n, m) = map(int, input().split())
	ab = [list(map(int, input().split())) for i in range(m)]
	ab.sort()
	arr_a = [ab[i][0] for i in range(m)]
	sa = [0]
	for i in range(m):
		sa.append(sa[-1] + arr_a[i])
	arr_b = [ab[i][1] for i in range(m)]
	ans = 0
	for (a, b) in ab:
		pos = bisect_left(arr_a, b)
		cnt = min(m - pos, n)
		res = sa[m] - sa[m - cnt] + b * (n - cnt)
		if a < b and n - cnt != 0:
			res += a - b
		ans = max(ans, res)
	print(ans)
	tmp = input()


from sys import stdin, stdout
t = int(stdin.readline())
for k in range(t):
	(n, m) = map(int, stdin.readline().split())
	abs_list = []
	for _ in range(m):
		abs_list.append(list(map(int, stdin.readline().split())))
	abs_list.sort(key=lambda x: -x[0])
	abs_list[0].append(abs_list[0][0])
	for i in range(1, m):
		abs_list[i].append(abs_list[i - 1][2] + abs_list[i][0])
	res = 0
	for i in range(m):
		if abs_list[i][1] > abs_list[0][0]:
			res = max(res, abs_list[i][0] + (n - 1) * abs_list[i][1])
			continue
		(l, h) = (0, m - 1)
		while l < h:
			mid = (l + h + 1) // 2
			if abs_list[mid][0] < abs_list[i][1]:
				h = mid - 1
			else:
				l = mid
		if l + 1 >= n:
			res = max(res, abs_list[n - 1][2])
		elif i <= l:
			res = max(res, abs_list[l][2] + (n - l - 1) * abs_list[i][1])
		else:
			res = max(res, abs_list[l][2] + abs_list[i][0] + (n - l - 2) * abs_list[i][1])
	stdout.write(str(res) + '\n')
	if k != t - 1:
		stdin.readline()


from sys import stdin

def solve():
	(n, m) = [int(i) for i in stdin.readline().split()]
	s = []
	for i in range(m):
		s.append(tuple((int(j) for j in stdin.readline().split())))
	s.sort(reverse=True)
	g = [0] * (m + 1)
	for i in range(1, m + 1):
		g[i] = g[i - 1] + s[i - 1][0]
	ans = 0
	for i in range(m):
		l = -1
		r = m
		while r - l > 1:
			mid = (l + r) // 2
			if s[mid][0] < s[i][1]:
				r = mid
			else:
				l = mid
		r = min(r, n)
		ann = 0
		ann += g[r]
		other = n - r
		if r <= i and r < n:
			ann += s[i][0]
			other -= 1
		ann += s[i][1] * other
		ans = max(ans, ann)
	print(ans)
q = int(stdin.readline())
for space in range(q):
	solve()
	if space < q - 1:
		stdin.readline()


import io
import os
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect

def solve(N, M, AB):
	AB.sort()
	A = []
	pref = [0]
	for (a, b) in AB:
		A.append(a)
		pref.append(pref[-1] + a)
	best = float('-inf')
	for (j, (a, b)) in enumerate(AB):
		i = bisect(A, b)
		i = max(i, M - N)
		used = M - i
		cost = pref[M] - pref[i]
		if N - used > 0:
			if j < i:
				cost += a
				used += 1
			if N - used > 0:
				cost += b * (N - used)
		best = max(best, cost)
	return best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, M) = [int(x) for x in input().split()]
	AB = [[int(x) for x in input().split()] for i in range(M)]
	input()
	ans = solve(N, M, AB)
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
Q = int(input())
for test in range(Q):
	(t, n) = map(int, input().split())
	ba = [list(map(int, input().split())) for _ in range(n)]
	ba.sort()
	bb = [b for (b, a) in ba]
	sumb = [0] + [b for (b, a) in ba[::-1]]
	for i in range(n):
		sumb[i + 1] += sumb[i]
	ans = 0
	from bisect import bisect_left, bisect_right
	for i in range(n):
		k = n - bisect_left(bb, ba[i][1])
		if n - i <= min(k, t):
			ans = max(ans, ba[i][1] * (t - min(k, t)) + sumb[min(k, t)])
		else:
			ans = max(ans, ba[i][1] * (t - min(k + 1, t)) + ba[i][0] + sumb[min(k, t - 1)])
	print(ans)
	if test == Q - 1:
		break
	s = input()