You are playing another computer game, and now you have to slay $n$ monsters. These monsters are standing in a circle, numbered clockwise from $1$ to $n$. Initially, the $i$-th monster has $a_i$ health.

You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by $1$ (deals $1$ damage to it). Furthermore, when the health of some monster $i$ becomes $0$ or less than $0$, it dies and explodes, dealing $b_i$ damage to the next monster (monster $i + 1$, if $i < n$, or monster $1$, if $i = n$). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.

You have to calculate the minimum number of bullets you have to fire to kill all $n$ monsters in the circle.


-----Input-----

The first line contains one integer $T$ ($1 \le T \le 150000$) — the number of test cases.

Then the test cases follow, each test case begins with a line containing one integer $n$ ($2 \le n \le 300000$) — the number of monsters. Then $n$ lines follow, each containing two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le 10^{12}$) — the parameters of the $i$-th monster in the circle.

It is guaranteed that the total number of monsters in all test cases does not exceed $300000$.


-----Output-----

For each test case, print one integer — the minimum number of bullets you have to fire to kill all of the monsters.


-----Examples-----

Input
1
3
7 15
2 14
5 3
Output
6


-----Note-----

None

Difficulty: MEDIUM_HARD

Solutions:
from sys import stdin
input = stdin.buffer.readline
N = int(input())
for Num in range(N):
	num1 = int(input())
	list1 = []
	bull = 0
	prev = 0
	for _ in range(num1):
		(p, q) = map(int, input().split())
		list1.append([p, q])
		if len(list1) != 1:
			if p > prev:
				bull = bull + p - prev
				p = prev
		list1[_][0] = p
		prev = q
	if list1[0][0] > prev:
		bull = bull + list1[0][0] - prev
		list1[0][0] = prev
	bull += min(list1)[0]
	print(bull)


import os
import sys
import math
from io import BytesIO, IOBase
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

def dijkstra(start, distance, path, n):
	visited = [False for _ in range(n)]
	distance[start] = 0
	for i in range(n):
		v = -1
		for j in range(n):
			if not visited[v] and (v == -1 or distance[j] < distance[v]):
				v = j
		if distance[v] == math.inf:
			break
		visited[v] = True
		for edge in adj[v]:
			destination = edge[0]
			weight = edge[1]
			if distance[v] + weight < distance[destination]:
				distance[destination] = distance[v] + weight
				path[destination] = v

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

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

def ncr(n, r):
	return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def npr(n, r):
	return math.factorial(n) // math.factorial(n - r)

def seive(n):
	primes = [True] * (n + 1)
	ans = []
	for i in range(2, n):
		if not primes[i]:
			continue
		j = 2 * i
		while j <= n:
			primes[j] = False
			j += i
	for p in range(2, n + 1):
		if primes[p]:
			ans += [p]
	return ans

def factors(n):
	factors = []
	x = 1
	while x * x <= n:
		if n % x == 0:
			if n // x == x:
				factors.append(x)
			else:
				factors.append(x)
				factors.append(n // x)
		x += 1
	return factors

def main():
	try:
		for _ in range(inp()):
			n = inp()
			(a, b) = ([], [])
			for i in range(n):
				(ai, bi) = invr()
				a += [ai]
				b += [bi]
			mn = math.inf
			ans = 0
			for i in range(n):
				ans += max(0, a[(i + 1) % n] - b[i])
				mn = min(mn, min(a[(i + 1) % n], b[i]))
			ans += mn
			print(ans)
	except Exception as e:
		print(e)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from math import *
from sys import *
from heapq import *
from collections import defaultdict
from itertools import permutations
import os, sys
from io import IOBase, BytesIO
M = 10 ** 9 + 7

def graph_as_tree_1_root():
	n = int(input())
	dict = defaultdict(list)
	for _ in range(n - 1):
		(x, y) = list(map(int, input().split()))
		dict[x].append(y)
		dict[y].append(x)
	tree = [[1]]
	temp = [1]
	vall = 0
	seen = set([i for i in range(2, n + 1)])
	lol = []
	while len(seen) > 0:
		lol = list(seen)
		tt = []
		for x in temp:
			aa = []
			for val in dict[x]:
				if val in seen:
					aa += [val]
					seen.remove(val)
			dict[x] = aa
			tt += aa
		tree.append(tt)
		temp = tt
		vall += 1
	for x in lol:
		dict[x] = []
	print(tree, dict)

def pow(a, b):
	res = 1
	while b > 0:
		if b & 1:
			res *= a
		a *= a
		b >>= 1
	return res

def powmod(a, b, m):
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b //= 2
	return res

def inv(a, m):
	return powmod(a, m - 2, m)

def alldivisors(n):
	list = []
	arr = []
	for i in range(1, int(sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				arr += [i]
			else:
				arr += [i]
				list.append(n // i)
	arr += list[::-1]
	return arr

def primefactorisation(n):
	potentional_p = 3
	itog_list = defaultdict(int)
	if n % 2 == 0:
		itog_list[2] = 0
	while n % 2 == 0:
		n = n // 2
		itog_list[2] += 1
	while n - 1:
		if potentional_p > n ** 0.5:
			itog_list[n] += 1
			return itog_list
		while n % potentional_p == 0:
			n = n // potentional_p
			itog_list[potentional_p] += 1
		potentional_p += 2
	return itog_list

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = []
		b = []
		for __ in range(n):
			(x, y) = list(map(int, input().split()))
			a.append(x)
			b.append(y)
		sm = max(0, a[0] - b[-1])
		a[0] -= max(0, a[0] - b[-1])
		for i in range(1, n):
			sm += max(0, a[i] - b[i - 1])
			a[i] -= max(0, a[i] - b[i - 1])
		stdout.write(str(sm + min(a)) + '\n')
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

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


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(a, b) = (int(x) for x in input().split())
	s = 0
	min_diff = float('inf')
	for i in range(n - 1):
		(an, bn) = (int(x) for x in input().split())
		dmg = max(0, an - b)
		s += dmg
		min_diff = min(min_diff, an - dmg)
		b = bn
	dmg = max(0, a - b)
	s += dmg
	min_diff = min(min_diff, a - dmg)
	sys.stdout.write(str(s + min_diff) + '\n')


import math
import sys
from collections import defaultdict, Counter, deque, OrderedDict
import bisect
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]
from itertools import accumulate, groupby
for _ in range(int(input())):
	N = int(input())
	A = []
	for i in range(N):
		(a, b) = ilele()
		A.append((a, b))
	A = A + A
	pre = [0]
	for i in range(1, len(A)):
		if A[i - 1][1] >= A[i][0]:
			pre.append(pre[-1])
		else:
			pre.append(A[i][0] - A[i - 1][1] + pre[-1])
	Ans = 1e+18
	for i in range(N):
		x = A[i][0] + pre[i + N - 1] - pre[i]
		Ans = min(Ans, x)
	print(Ans)


from sys import stdin, stdout
import io, os
input = stdin.buffer.readline
l = []
for _ in range(int(input())):
	n = int(input())
	(a, b) = zip(*[list(map(int, input().split())) for i in range(n)])
	(ans, mi) = (0, 10 ** 18)
	for i in range(n):
		ans += max(0, a[i] - b[i - 1])
		mi = min(mi, a[i] - max(0, a[i] - b[i - 1]))
	l.append(str(mi + ans) + '\n')
stdout.writelines(l)


import sys
I = sys.stdin.buffer.readline
for _ in [0] * int(I()):
	(a, b) = zip(*(map(int, I().split()) for _ in [0] * int(I())))
	b = [min(x, y) for (x, y) in zip(b, a[1:] + a[:1])]
	print(sum(a) - sum(b) + min(b))


import sys
input = sys.stdin.buffer.read

class GetInt:

	def __init__(self):
		self.nums = list(map(int, input().split()))
		self.n_idx = -1

	def get(self):
		self.n_idx += 1
		return self.nums[self.n_idx]
inp = GetInt()
T = inp.get()
fans = []
for _ in range(T):
	ans = 0
	A = []
	B = []
	n = inp.get()
	for i in range(n):
		(a, b) = (inp.get(), inp.get())
		A.append(a)
		B.append(b)
	for i in range(n):
		B[i] = min(B[i], A[(i + 1) % n])
	for i in range(n):
		ans += A[i] - B[(i - 1 + n) % n]
	fans.append(str(ans + min(B)))
print('\n'.join(fans))


import os
import sys
from io import BytesIO, IOBase
from math import gcd, inf, sqrt

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

def getFactorization(x):
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

def printDivisors(n):
	i = 2
	z = [1, n]
	while i <= sqrt(n):
		if n % i == 0:
			if n / i == i:
				z.append(i)
			else:
				z.append(i)
				z.append(n // i)
		i = i + 1
	return z

def cheaker(a):
	j = 1
	p = False
	for i in a:
		if i != j:
			break
		j += 1
	q = len(a)
	for i in a[::-1]:
		if i != q:
			break
		q -= 1
	for i in range(j - 1, q):
		if a[i] == i + 1:
			return False
	return True

def create(n, x, f):
	pq = len(bin(n)[2:])
	if f == 0:
		tt = min
	else:
		tt = max
	dp = [[inf] * n for _ in range(pq)]
	dp[0] = x
	for i in range(1, pq):
		for j in range(n - (1 << i) + 1):
			dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << i - 1)])
	return dp

def enquiry(l, r, dp, f):
	if l > r:
		return inf if not f else -inf
	if f == 1:
		tt = max
	else:
		tt = min
	pq1 = len(bin(r - l + 1)[2:]) - 1
	return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1])

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	x = []
	for i in range(2, n + 1):
		if prime[i]:
			x.append(i)
	return x

def main():
	from math import inf
	for _ in range(int(input())):
		n = int(input())
		(a, b) = ([0 for x in range(n)], [0 for x in range(n)])
		for i in range(n):
			(a[i], b[i]) = map(int, input().split())
		an = a[:]
		for i in range(n):
			an[i] -= b[i - 1]
			an[i] = max(an[i], 0)
		an = an + an
		for i in range(1, len(an)):
			an[i] += an[i - 1]
		for i in range(n):
			an[i] = an[i + n - 1] - an[i]
		m = inf
		for i in range(n):
			m = min(an[i] + a[i], m)
		print(m)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import sys

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

def mdata():
	return map(int, data().split())
for t in range(int(data())):
	n = int(data())
	(a, b) = mdata()
	(a1, b1) = (a, b)
	k = s = a1
	for i in range(n - 1):
		(x, y) = mdata()
		if x > b:
			s = s + x - b
			k = min(b, k)
		else:
			k = min(k, x)
		b = y
	k = min(k, min(a1, b))
	s = s - min(a1, b) + k
	sys.stdout.write(str(s) + '\n')


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for i in range(int(input())):
	n = int(input())
	a = []
	b = []
	for i in range(n):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	s = 0
	for i in range(n):
		v = a[(i + 1) % n]
		val = max(0, v - b[i])
		s += val
	z = 10 ** 18 + 100
	for i in range(n):
		v = a[(i + 1) % n]
		z = min(z, v - max(0, v - b[i]))
	s += z
	print(s)


import sys
input = sys.stdin.buffer.readline

def prog():
	for _ in range(int(input())):
		n = int(input())
		circle = [list(map(int, input().split())) for i in range(n)]
		shot = 0
		for i in range(n):
			curr = circle[i]
			j = (i - 1) % n
			previous = circle[j][1]
			if curr[0] > previous:
				shot += curr[0] - previous
				curr[0] = previous
		shot += min(circle, key=lambda x: x[0])[0]
		sys.stdout.write(str(shot) + '\n')
prog()


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 sys import stdin, stdout
t = int(input())
for i in range(t):
	n = int(input())
	l = []
	l1 = []
	s = 0
	s1 = 0
	l4 = []
	for j in range(n):
		ll = list(map(int, stdin.readline().split()))
		l1.append(ll[0])
		s1 += ll[0]
		if j != 0:
			x = ll[0] - l[-1][1]
			if x > 0:
				s += x
				l4.append(x)
			else:
				l4.append(0)
		l.append(ll)
	if l[0][0] - l[-1][1] > 0:
		s += l[0][0] - l[-1][1]
		l4 = [l[0][0] - l[-1][1]] + l4
	else:
		l4 = [0] + l4
	ans = s1
	for j in range(n):
		ans = min(ans, l1[j] + s - l4[j])
	print(ans)


from sys import stdin
T = int(stdin.buffer.readline())
for _ in range(T):
	n = int(stdin.buffer.readline())
	a = []
	b = []
	for __ in range(n):
		(a_i, b_i) = map(int, stdin.buffer.readline().split())
		a.append(a_i)
		b.append(b_i)
	sum = 0
	res = float('inf')
	for i in range(n):
		if a[i] >= b[(i - 1 + n) % n]:
			d = a[i] - b[(i - 1 + n) % n]
		else:
			d = 0
		sum += d
		res = min(res, a[i] - d)
	print(sum + res)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	c = []
	sum = 0
	m = 10 ** 20
	for i in range(n):
		c.append(list(map(int, input().split())))
		if i > 0:
			x = c[i][0]
			y = max(0, c[i][0] - c[i - 1][1])
			sum += y
			m = min(x - y, m)
	x = c[0][0]
	y = max(0, c[0][0] - c[-1][1])
	sum += y
	m = min(x - y, m)
	print(sum + m)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	c = [0 for _ in range(n)]
	c_sum = 0
	for i in range(n):
		if i == 0:
			x = max(0, a[0] - b[n - 1])
		else:
			x = max(0, a[i] - b[i - 1])
		c[i] = x
		c_sum += x
	ans = 10 ** 20
	for i in range(n):
		ans = min(ans, c_sum - c[i] + a[i])
	print(ans)


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 main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		health = []
		damage = []
		delSum = 0
		tempMin = 10 ** 12
		minHealth = 10 ** 12
		tempH = None
		zeroH = None
		tempD = None
		zeroD = None
		for i in range(n):
			(h, d) = map(int, input().split())
			health.append(h)
			damage.append(d)
			minHealth = min(minHealth, h)
			if i == 0:
				zeroH = h
				zeroD = d
			if i != 0:
				delSum += max(0, h - tempD)
				tempMin = min(tempMin, h - max(0, h - tempD))
			if i == n - 1:
				delSum += max(0, zeroH - d)
				tempMin = min(tempMin, zeroH - max(0, zeroH - d))
			tempH = h
			tempD = d
		if delSum == 0:
			print(minHealth)
			continue
		minVal = delSum + tempMin
		print(minVal)
	return
main()


import os, sys
inp = os.read(0, int(10000000.0)).split()
inp_pos = 0

def input():
	global inp_pos
	inp_pos += 1
	return inp[inp_pos - 1]
T = int(input())
ans = []
for tt in range(T):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		a.append(int(input()))
		b.append(int(input()))
	minv = 4557430888798830399
	total = 0
	for i in range(n):
		j = i - 1 if i > 0 else n - 1
		total += max(0, a[i] - b[j])
		minv = min(minv, a[i], b[j])
	ans.append(str(total + minv).encode('ascii'))
os.write(1, '\n'.encode().join(ans))


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		(a1, b1) = map(int, input().split())
		a.append(a1)
		b.append(b1)
	sm = 0
	for i in range(n):
		sm += max(0, a[i] - b[i - 1])
	mn = sm + a[0] - max(0, a[0] - b[n - 1])
	for i in range(1, n):
		mn = min(mn, sm + a[i] - max(0, a[i] - b[i - 1]))
	print(mn)


import sys
input = sys.stdin.readline
INF = 1001002003004005006

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		(ans, mi, blast) = (0, INF, 0)
		for i in range(n):
			(a, b) = map(int, input().split())
			if i:
				if a > blast:
					ans += a - blast
					mi = min(mi, blast)
				else:
					mi = min(mi, a)
			else:
				a0 = a
			blast = b
		ans += max(0, a0 - blast)
		mi = min(mi, min(a0, blast))
		print(ans + mi)
	return
main()


import sys

def solve():
	t = int(sys.stdin.readline())
	for _ in range(t):
		n = int(sys.stdin.readline())
		blast = 0
		minb = 0
		s = 0
		a0 = 0
		for i in range(n):
			(ai, bi) = map(int, sys.stdin.readline().split())
			bbigger = False
			if i != 0:
				if i > 1:
					if ai >= blast:
						minb = min(minb, blast)
					else:
						bbigger = True
						minb = min(minb, ai)
				elif ai >= blast:
					minb = blast
				else:
					bbigger = True
					minb = ai
				if not bbigger:
					s += ai - blast
			else:
				a0 = ai
			blast = bi
		s += max(0, a0 - blast)
		minb = min(minb, min(a0, blast))
		print(s + minb)
solve()


import sys
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	for i in range(n):
		b[i] = min(a[(i + 1) % n], b[i])
	b[-1] = min(a[0], b[-1])
	print(sum(a) - sum(b) + min(b))


import sys
input = sys.stdin.buffer.readline
t = int(input())
ans = []
for _ in range(t):
	n = int(input())
	a = [0] * n
	b = [0] * n
	total = 0
	minA = -1
	for i in range(n):
		(a1, b1) = map(int, input().split())
		a[i] = a1
		b[i] = b1
		if not i == 0:
			x = max(0, a[i] - b[i - 1])
			total += x
			if minA == -1:
				minA = a[i] - x
			else:
				minA = min(minA, a[i] - x)
	total += max(0, a[0] - b[n - 1])
	minA = min(minA, a[0] - max(0, a[0] - b[n - 1]))
	ans.append(total + minA)
print('\n'.join(map(str, ans)))


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	(x, y) = map(int, input().split())
	(a, b) = (x, y)
	suma = 0
	mini = float('inf')
	for __ in range(n - 1):
		(x, y) = map(int, input().split())
		dmg = max(x - b, 0)
		suma += dmg
		mini = min(x - dmg, mini)
		b = y
	dmg = max(a - b, 0)
	suma += dmg
	mini = min(a - dmg, mini)
	sys.stdout.write(str(suma + mini) + '\n')


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	a = [[int(i) for i in input().split()] for j in range(n)]
	s = max(0, a[0][0] - a[-1][1])
	mn = min(a[0][0] - s, min((a[i][0] - max(0, a[i][0] - a[i - 1][1]) for i in range(1, n))))
	print(s + sum((max(0, a[i][0] - a[i - 1][1]) for i in range(1, n))) + mn)


import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
t = int(input())
for case in range(t):
	n = int(input())
	a = [0] * n
	b = [0] * n
	c = [0] * n
	min_c = 10 ** 13
	sum_a = 0
	sum_c = 0
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
		sum_a += a[i]
		if i > 0:
			c[i] = min(b[i - 1], a[i])
			sum_c += c[i]
			if c[i] < min_c:
				min_c = c[i]
	c[0] = min(b[-1], a[0])
	sum_c += c[0]
	if c[0] < min_c:
		min_c = c[0]
	ans = sum_a - sum_c + min_c
	print(ans)


from sys import stdin, gettrace

def input():
	return stdin.buffer.readline()

def main():

	def solve():
		n = int(input())
		li = []
		for i in range(n):
			temp = [int(x) for x in input().split()]
			li.append(temp)
			if i == 0:
				ans = li[0][0]
			else:
				ans += max(0, li[i][0] - li[i - 1][1])
		ans_final = 9999999999999999999999999999999999999
		for i in range(1, n):
			ans_temp = ans - li[(i - 1) % n][0] + max(0, li[(i - 1) % n][0] - li[(i + n - 2) % n][1]) + li[i][0] - max(li[i][0] - li[(i - 1) % n][1], 0)
			ans_final = min(ans, ans_temp, ans_final)
			ans = ans_temp
		print(ans_final)
	q = int(input())
	for _ in range(q):
		solve()
main()


import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	n = int(input())
	arr = []
	brr = []
	for _ in range(n):
		(a, b) = map(int, input().split())
		a = int(a)
		b = int(b)
		arr.append(a)
		brr.append(b)
	total = []
	for i in range(n):
		total.append(max(0, arr[i] - brr[i - 1]))
	T = sum(total)
	minn = float('inf')
	for j in range(n):
		minn = min(minn, T + arr[j] - total[j])
	sys.stdout.write(str(minn) + '\n')


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

def answer(n, ab):
	cost2 = [0 for _ in range(n)]
	cost2[0] = max(ab[0][0] - ab[n - 1][1], 0)
	summ = cost2[0]
	for i in range(1, n):
		cost2[i] = max(ab[i][0] - ab[i - 1][1], 0)
		summ += cost2[i]
	cost_st_i = [0 for _ in range(n)]
	mn = 10 ** 23
	for i in range(n):
		cost_st_i[i] = summ - cost2[i] + ab[i][0]
		mn = min(mn, cost_st_i[i])
	return mn

def main():
	T = int(input())
	while T:
		n = int(input())
		ab = [tuple(map(int, input().split())) for _ in range(n)]
		print(answer(n, ab))
		T -= 1
	return
main()


from collections import Counter
from math import inf
from sys import stdin
import collections
import os
import sys
from io import IOBase, BytesIO
from sys import stdin, stdout
from math import sqrt
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange

def main():
	for test in range(int(input())):
		n = int(input())
		a = [0] * n
		b = [0] * n
		for i in range(n):
			(a[i], b[i]) = map(int, input().split())
		b[n - 1] = min(a[0], b[n - 1])
		for i in range(n - 1):
			b[i] = min(b[i], a[i + 1])
		print(sum(a) - sum(b) + min(b))
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

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

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

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'
main()


def main():
	import io, os
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
	import sys
	T = int(input())
	for tests in range(T):
		n = int(input())
		M = [list(map(int, input().split())) for i in range(n)]
		ANS = 0
		for i in range(n):
			if M[i][0] > M[i - 1][1]:
				ANS += M[i][0] - M[i - 1][1]
				M[i][0] = M[i - 1][1]
		MIN = M[0][0]
		for i in range(n):
			MIN = min(MIN, M[i][0])
		sys.stdout.write(str(ANS + MIN) + '\n')
import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.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(io.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):
	for x in args:
		file.write(str(x))
	file.write(kwargs.pop('end', '\n'))
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inputt = lambda t=0: range(t) if t else range(int(input()))
inputi = lambda : map(int, input().split())
inputl = lambda : list(inputi())
from math import *
from heapq import *
from bisect import *
from itertools import *
from functools import reduce, lru_cache
from collections import Counter, defaultdict
import re, copy, operator, cmath
from builtins import *
main()


import sys
input = sys.stdin.buffer.readline
tests = int(input())
for ii in range(tests):
	n = int(input())
	a = []
	b = []
	for i in range(1, n + 1):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	sum = 0
	a.append(a[0])
	b.append(b[0])
	for i in range(1, n + 1):
		sum += max(a[i] - b[i - 1], 0)
	ans = sum + a[1]
	for i in range(1, n + 1):
		ans = min(ans, sum + a[i] - max(a[i] - b[i - 1], 0))
	sys.stdout.write(str(ans) + '\n')


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for t in range(int(input())):
	n = int(input())
	A = [0] * n
	B = [0] * n
	for i in range(n):
		(A[i], B[i]) = [int(s) for s in input().split()]
	minB = B[0]
	ans = 0
	for i in range(-1, n - 1):
		if B[i] > A[i + 1]:
			B[i] = A[i + 1]
		minB = min(minB, B[i])
		ans += A[i] - B[i]
	ans += minB
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
test = int(input())
for _ in range(test):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	for i in range(n - 1):
		b[i] = min(b[i], a[i + 1])
	b[-1] = min(b[-1], a[0])
	print(sum(a) - sum(b) + min(b))


import os
pos = 0
inp = os.read(0, int(10000000.0)).split()
T = int(inp[pos])
pos += 1
ans = []
tt = 0
while tt < T:
	n = int(inp[pos])
	pos += 1
	i = 0
	minv = 4557430888798830399
	total = 0
	while i < n:
		a = int(inp[pos])
		pos += 1
		b = int(inp[pos])
		pos += 1
		if i == 0:
			firsta = a
		else:
			total += max(0, a - pb)
		minv = min(minv, a, b)
		pb = b
		i += 1
	total += max(0, firsta - b)
	ans.append(str(total + minv).encode())
	tt += 1
os.write(1, '\n'.encode().join(ans))


from sys import stdin

def input():
	return stdin.buffer.readline()
for _ in range(int(input())):
	n = int(input())
	(a, b) = (list(), list())
	for __ in range(n):
		(ai, bi) = map(int, input().split())
		a.append(ai)
		b.append(bi)
	gain = [0] * n
	gain[0] = min(a[0], b[n - 1])
	(imin, gmin) = (0, gain[0])
	for i in range(1, n):
		gain[i] = min(a[i], b[i - 1])
		if gain[i] < gmin:
			imin = i
			gmin = gain[i]
	out = a[imin]
	a[0] = max(0, a[0] - b[n - 1])
	for i in range(n):
		if i == imin:
			continue
		if i != 0:
			a[i] = max(0, a[i] - b[i - 1])
		out += a[i]
	print(out)


import sys

def solve():
	input = sys.stdin.buffer.readline
	t = int(input())
	while t > 0:
		n = int(input())
		a = []
		b = []
		cnt = 0
		mn = float('inf')
		for i in range(n):
			(x, y) = map(int, input().split())
			a.append(x)
			b.append(y)
		for i in range(n):
			extra = max(0, a[i] - b[i - 1])
			mn = min(mn, a[i] - extra)
			cnt += extra
		cnt += mn
		sys.stdout.write(str(cnt) + '\n')
		t -= 1
solve()


import sys
input = sys.stdin.buffer.readline

def calc(i, sub):
	i = n - 1
	while i >= 0:
		if i == n - 1:
			dp[i] = max(0, l[i][0] - l[i - 1][1])
			i -= 1
			continue
		if i == 0:
			dp[i] = l[i][0] + dp[i + 1]
			break
		if l[i - 1][1] < l[i][0]:
			dp[i] = l[i][0] - l[i - 1][1] + dp[i + 1]
		elif l[i - 1][1] >= l[i][0]:
			dp[i] = 0 + dp[i + 1]
		i -= 1
for nt in range(int(input())):
	n = int(input())
	l = []
	dp = []
	for i in range(n):
		(a, b) = map(int, input().split())
		l.append((a, b))
		dp.append(0)
	calc(0, 0)
	last = max(0, l[0][0] - l[-1][1])
	ans = dp[0]
	for i in range(1, n - 1):
		a = l[i][0] + dp[i + 1] + last + dp[1] - dp[i]
		ans = min(ans, a)
	ans = min(ans, l[-1][0] + last + dp[1] - dp[-1])
	print(ans)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	count = 0
	a = []
	b = []
	for l in range(n):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	for i in range(n):
		if a[i] - b[i - 1] > 0:
			count += a[i] - b[i - 1]
			a[i] = b[i - 1]
	minimum = min(a)
	count += minimum
	print(count)


from sys import stdin
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 inp():
	return int(input())

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

def main():
	t = inp()
	for _ in range(t):
		n = inp()
		(A, B) = zip(*[arrinp() for i in range(n)])
		(ans, min_cost) = (0, float('inf'))
		for i in range(n):
			ans += max(A[i] - B[i - 1], 0)
			min_cost = min(min_cost, A[i] - max(0, A[i] - B[i - 1]))
		print(min_cost + ans)
main()


import sys, os
maxn = 300000
(a, b, d) = ([0] * maxn, [0] * maxn, [0] * maxn)
input = sys.stdin.buffer.readline
for t in range(int(input())):
	n = int(input())
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
	d[0] = a[0] - b[n - 1]
	for i in range(1, n):
		d[i] = a[i] - b[i - 1]
	ans = 0
	for i in range(n):
		if d[i] > 0:
			ans += d[i]
	best = 1 << 40
	for i in range(n):
		if d[i] <= 0:
			best = min(best, a[i])
		else:
			best = min(best, a[i] - d[i])
	print(ans + best)


import os
import sys
from io import BytesIO, IOBase
import threading
from collections import defaultdict, Counter
from math import factorial as fac

def main():
	t = int(input())
	for v in range(t):
		n = int(input())
		adj = []
		prefix = []
		prefix.append(0)
		for i in range(n):
			li = list(map(int, input().split(' ')))
			adj.append(li)
			if i != 0:
				prefix.append(adj[i][0] - adj[i - 1][1])
		prefix[0] = adj[0][0] - adj[n - 1][1]
		ans = []
		sum = adj[0][0]
		for i in range(1, n):
			if prefix[i] > 0:
				sum += prefix[i]
		ans.append(sum)
		mi = ans[0]
		for i in range(1, n):
			sum = ans[i - 1]
			sum += adj[i][0] - adj[i - 1][0]
			if prefix[i] > 0:
				sum -= prefix[i]
			if prefix[i - 1] > 0:
				sum += prefix[i - 1]
			ans.append(sum)
			mi = min(sum, mi)
		print(mi)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from sys import stdin, gettrace

def input():
	return stdin.buffer.readline()
t = int(input())
for _ in range(t):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		(a_i, b_i) = list(map(int, input().split()))
		a.append(a_i)
		b.append(b_i)
	for i in range(n):
		b[i - 1] = min(b[i - 1], a[i])
	print(sum(a) - sum(b) + min(b))


import os
inp = os.read(0, int(10000000.0)).split()
inp_pos = 0

def input():
	global inp_pos
	inp_pos += 1
	return inp[inp_pos - 1]
tc = int(input())
for _ in range(tc):
	n = int(input())
	monsters = []
	for i in range(n):
		(h, d) = (int(input()), int(input()))
		monsters.append((i, h, d))
	rem = []
	for i in range(n):
		dmg = monsters[(i + n - 1) % n][2]
		h = monsters[i][1]
		rem_h = max(h - dmg, 0)
		rem.append((h - rem_h, rem_h))
	s = sum((v[1] for v in rem))
	print(s + min(rem)[0], flush=False)


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')
t = int(input())
for _ in range(t):
	n = int(input())
	stats = list()
	for _ in range(n):
		(a, b) = map(int, input().split())
		stats.append((a, b))
	bullets = 0
	for idx in range(len(stats)):
		prev_idx = (idx - 1 + n) % n
		bullets += max(stats[idx][0] - stats[prev_idx][1], 0)
	ans = 10 ** 20
	for idx in range(len(stats)):
		prev_idx = (idx - 1 + n) % n
		already_shot = max(stats[idx][0] - stats[prev_idx][1], 0)
		ans = min(ans, bullets - already_shot + stats[idx][0])
	print(ans)


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	pass
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 binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(int(n))
	return l

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

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)
for xyz in range(0, int(input())):
	n = int(input())
	l = []
	t = []
	for i in range(0, n):
		l.append(list(map(int, input().split())))
	for i in range(0, n):
		t.append(max(0, l[(i + 1) % n][0] - l[i][1]))
	a = sum(t)
	bd = 10000000000000
	for i in range(0, n):
		bd = min(bd, min(l[i][1], l[(i + 1) % n][0]))
	print(a + bd)


from collections import defaultdict as dd
from collections import deque
from sys import stdin
import bisect
import heapq
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 ri():
	return int(input())

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

def solve():
	n = ri()
	min_diff = 10 ** 20
	total_cost = 0
	(pa, pb) = rl()
	(oa, ob) = (pa, pb)
	for i in range(n - 1):
		(a, b) = rl()
		cheap = max(a - pb, 0)
		diff = a - cheap
		min_diff = min(min_diff, diff)
		total_cost += cheap
		(pa, pb) = (a, b)
	cheap = max(oa - b, 0)
	diff = oa - cheap
	min_diff = min(min_diff, diff)
	total_cost += cheap
	print(total_cost + min_diff)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


from collections import Counter
from collections import defaultdict
import math
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
t = int(input())
for _ in range(0, t):
	n = int(input())
	a = []
	b = []
	for i in range(0, n):
		(l1, l2) = list(map(int, input().split()))
		a.append(l1)
		b.append(l2)
	index = -1
	s = 0
	l = []
	for i in range(0, n):
		mx = max(0, a[i] - b[i - 1])
		s = s + mx
	mn = float('inf')
	for i in range(0, n):
		mn = min(mn, s - max(0, a[i] - b[i - 1]) + a[i])
	sys.stdout.write(str(mn) + '\n')


import sys
input = sys.stdin.buffer.readline
t = int(input())
for k in range(t):
	arr = []
	ls = []
	n = int(input())
	for j in range(n):
		(h, d) = map(int, input().split())
		arr.append(h)
		ls.append(d)
	for i in range(n - 1):
		ls[i] = min(ls[i], arr[i + 1])
	ls[-1] = min(ls[-1], arr[0])
	print(sum(arr) - sum(ls) + min(ls))


import sys
input = sys.stdin.buffer.readline

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		(hp, dmg) = ([], [])
		for _ in range(n):
			(a, b) = map(int, input().split())
			hp.append(a)
			dmg.append(b)
		for i in range(n):
			dmg[i - 1] = min(hp[i], dmg[i - 1])
		print(sum(hp) - sum(dmg) + min(dmg))
main()


import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
t = int(input())
for i in range(t):
	n = int(input())
	a = []
	b = []
	for j in range(n):
		c = list(map(int, input().split()))
		a.append(c[0])
		b.append(c[1])
	for j in range(n):
		if b[j - 1] >= a[j]:
			b[j - 1] = a[j]
	y = min(b)
	s = sum(b) - y
	print(sum(a) - s)


from sys import stdin, stdout

def main():
	t = int(stdin.readline())
	for _ in range(t):
		n = int(stdin.readline())
		big = 1000000000001
		answer = 0
		(a_init, b) = map(int, stdin.readline().split())
		for _ in range(n - 1):
			(a, b_new) = map(int, stdin.readline().split())
			raz = min(a, b)
			if raz < big:
				big = raz
			answer += max(a - b, 0)
			b = b_new
		a = a_init
		raz = min(a, b)
		if raz < big:
			big = raz
		answer += max(a - b, 0)
		stdout.write('%d\n' % (answer + big))
	stdout.flush()
main()


import io, os
import sys
input = sys.stdin.buffer.readline
T = int(input())

def answer(n, a, b):
	cost2 = [0 for _ in range(n)]
	cost2[0] = max(a[0] - b[n - 1], 0)
	summ = cost2[0]
	for i in range(1, n):
		cost2[i] = max(a[i] - b[i - 1], 0)
		summ += cost2[i]
	cost_st_i = [0 for _ in range(n)]
	mn = 10 ** 23
	for i in range(n):
		cost_st_i[i] = summ - cost2[i] + a[i]
		mn = min(mn, cost_st_i[i])
	return mn

def main(T):
	while T:
		n = int(input())
		a = [0 for _ in range(n)]
		b = [0 for _ in range(n)]
		for i in range(n):
			(a[i], b[i]) = map(int, input().split())
		print(answer(n, a, b))
		T -= 1
	return
main(T)


import os, sys
inp = os.read(0, int(100000000.0)).split()
inp_pos = 0

def input():
	global inp_pos
	inp_pos += 1
	return inp[inp_pos - 1]
T = int(input())
ans = []
tt = 0
while tt < T:
	n = int(input())
	i = 0
	minv = 4557430888798830399
	total = 0
	while i < n:
		a = int(input())
		b = int(input())
		if i == 0:
			firsta = a
		else:
			total += max(0, a - pb)
		minv = min(minv, a, b)
		pb = b
		i += 1
	total += max(0, firsta - b)
	ans.append(str(total + minv).encode('ascii'))
	tt += 1
os.write(1, '\n'.encode().join(ans))


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(a, b) = ([], [])
	for __ in range(n):
		(ai, bi) = map(int, input().split())
		a.append(ai)
		b.append(bi)
	for i in range(n - 1):
		b[i] = min(b[i], a[i + 1])
	b[n - 1] = min(b[n - 1], a[0])
	print(sum(a) - sum(b) + min(b))


from sys import stdin, stdout
import io, os
input = stdin.buffer.readline

def inp():
	return int(input())

def arrinp():
	return [int(x) for x in input().split()]
l = []

def main():
	t = inp()
	for _ in range(t):
		n = inp()
		(A, B) = zip(*[list(map(int, input().split())) for i in range(n)])
		(ans, min_cost) = (0, float('inf'))
		for i in range(n):
			ans += max(A[i] - B[i - 1], 0)
			min_cost = min(min_cost, A[i] - max(0, A[i] - B[i - 1]))
		l.append(str(min_cost + ans) + '\n')
	stdout.writelines(l)
main()


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
import bisect, collections, heapq
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def solution():
	n = int(input().strip())
	arr = []
	for _ in range(n):
		arr.append([int(x) for x in input().strip().split()])
	if n == 1:
		print(arr[0][0])
		return
	(curSum, minStart) = (0, float('inf'))
	for i in range(n):
		tmp = max(0, arr[i][0] - arr[i - 1][1])
		minStart = min(minStart, arr[i][0] - tmp)
		curSum += tmp
	print(curSum + minStart)

def main():
	T = int(input().strip())
	for _ in range(T):
		solution()
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import os
import sys
from io import BytesIO, IOBase
import math
from decimal import *
getcontext().prec = 25
MOD = pow(10, 9) + 7
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())):
	n = int(input())
	ans = 0
	x = []
	mi = 0
	mini = 9999999999999999999
	for i in range(n):
		(a, b) = map(int, input().split())
		x.append((a, b))
	for i in range(n):
		ni = (i + 1) % n
		a = x[ni][0]
		b = x[i][1]
		test = a - max(0, a - b)
		if test < mini:
			mini = test
			mi = ni
	i = 0
	last = 0
	while i < n:
		ind = mi + i
		if ind >= n:
			ind -= n
		ans += max(x[ind][0] - last, 0)
		last = x[ind][1]
		i += 1
	print(ans)


import sys
input = sys.stdin.buffer.readline
T = int(input())
for iTest in range(T):
	w = int(input())
	a = [0] * w
	b = [0] * w
	for i in range(w):
		(a[i], b[i]) = map(int, input().split())
	b[w - 1] = min(a[0], b[w - 1])
	for i in range(w - 1):
		b[i] = min(b[i], a[i + 1])
	print(sum(a) - sum(b) + min(b))


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')
for _ in range(int(input())):
	a = []
	b = []
	n = int(input())
	for i in range(n):
		(ai, bi) = map(int, input().split())
		a.append(ai)
		b.append(bi)
	for i in range(n - 1):
		b[i] = min(a[i + 1], b[i])
	b[-1] = min(b[-1], a[0])
	print(sum(a) - sum(b) + min(b))


import os, sys, atexit
if sys.version_info[0] < 3:
	range = xrange
	from cStringIO import StringIO as BytesIO
	sys.stdout = BytesIO()
else:
	from io import BytesIO
	sys.stdout = BytesIO()
	_write = sys.stdout.write
	sys.stdout.write = lambda s: _write(s.encode())
atexit.register(lambda : os.write(1, sys.stdout.getvalue()))
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
from sys import stdin, stdout
(rints, out) = (lambda : [int(x) for x in input().split()], [])
for _ in range(int(input())):
	n = int(input())
	(a, all, ans) = ([rints() for _ in range(n)], 0, float('inf'))
	for i in range(n):
		all += max(a[i][0] - a[(i - 1) % n][1], 0)
	for i in range(n):
		tem = all - max(a[i][0] - a[(i - 1) % n][1], 0)
		ans = min(ans, a[i][0] + tem)
	out.append(str(ans))
stdout.write('\n'.join(out))


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from _collections import deque
import sys
import math
import heapq
import bisect
t = int(input())
for _ in range(t):
	n = int(input())
	a = [0] * n
	b = [0] * n
	answer = 0
	for i in range(n):
		(x, y) = map(int, input().split())
		a[i] = x
		b[i] = y
	for i in range(n):
		if a[i] > b[i - 1]:
			answer += a[i] - b[i - 1]
			a[i] = b[i - 1]
	answer += min(a)
	print(answer)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(health, damage) = ([], [])
	(a, b, _min) = (0, 0, 10 ** 15)
	for i in range(n):
		(h, d) = map(int, input().split())
		a += h
		health.append(h)
		damage.append(d)
	for i in range(n):
		damage[i] = min(health[(i + 1) % n], damage[i])
		b += damage[i]
		_min = min(_min, damage[i])
	print(a - b + _min)


input = __import__('sys').stdin.buffer.readline
t = int(input())
output = []
for tc in range(t):
	n = int(input())
	a = [0 for i in range(n)]
	b = [0 for i in range(n)]
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
	a += a
	b += b
	(p, xp) = (0, min(b[0], a[1]))
	for i in range(1, n):
		xp2 = min(b[i], a[i + 1])
		if xp2 < xp:
			(p, xp) = (i, xp2)
	sol = 0
	p += 1
	for k in range(p, p + n):
		i = k
		j = k + 1
		sol += a[i]
		if j < n + n:
			a[j] -= min(a[j], b[i])
	output.append(str(sol))
print('\n'.join(output))


from sys import stdin, stdout
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for test in range(t):
	n = int(input())
	mon = []
	for i in range(n):
		mon.append([int(x) for x in input().split()])
	req = []
	for i in range(n - 1):
		req.append(max(0, mon[i + 1][0] - mon[i][1]))
	req.append(max(0, mon[0][0] - mon[n - 1][1]))
	x = sum(req)
	ans = []
	for i in range(n):
		ans.append(x + mon[i][0] - req[i - 1])
	anss = min(ans)
	stdout.write(str(anss) + '\n')


from sys import stdin, stdout
R = lambda : stdin.readline().strip()
RL = lambda : list(map(int, R().split(' ')))
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
par = [[0, 0] for i in range(600000)]
for _ in range(t):
	n = int(input())
	for i in range(n):
		(a, b) = map(int, input().split())
		par[i][0] = a
		par[i][1] = b
		par[n + i][0] = a
		par[n + i][1] = b
	s = 0
	mn = 1e+18
	for i in range(n):
		par[n + i][0] = max(0, par[n + i][0] - par[n + i - 1][1])
		s += par[n + i][0]
	for i in range(n):
		mn = min(mn, par[i][0] + s - par[n + i][0])
	print(mn)


import sys
from itertools import islice
stdin = sys.stdin
T = int(stdin.readline())

def kill_mon(arr):
	last_explosion = arr[-1][1]
	bullets = 0
	mini = 100000000000000000000
	for (hp, exp) in arr:
		if hp > last_explosion:
			bullets += hp - last_explosion
		candidate = last_explosion if last_explosion < hp else hp
		if candidate < mini:
			mini = candidate
		last_explosion = exp
	return bullets + mini
for x in range(T):
	n = int(stdin.readline())
	monsters = [[int(y) for y in x.split()] for x in islice(stdin, n)]
	print(kill_mon(monsters))


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	A = [0] * n
	B = [0] * n
	for i in range(n):
		(a, b) = map(int, input().split())
		A[i] = a
		B[i] = b
	v = 10 ** 13
	ans = 0
	for i in range(n):
		e = max(0, A[i] - B[i - 1])
		v = min(v, A[i] - e)
		ans += e
	ans += v
	sys.stdout.write(str(ans) + '\n')


import sys, os
input = sys.stdin.buffer.read().split(b'\n')[::-1].pop
out = []

def print(x):
	out.append(str(x).encode('ascii'))

def next(st, n):
	if st == n - 1:
		return 0
	return st + 1
for t in range(int(input())):
	n = int(input())
	a = []
	b = []
	for i in range(n):
		(x, y) = [int(j) for j in input().split()]
		a.append(x)
		b.append(y)
	if n == 1:
		print(a[0])
		continue
	st = min(((b[i - 1], a[i], i) for i in range(n)))[2]
	num = 0
	bul = a[st]
	while num < n - 1:
		nx = next(st, n)
		bul += max(a[nx] - b[st], 0)
		st = nx
		num += 1
	ans = bul
	st = min(((a[i], b[i - 1], i) for i in range(n)))[2]
	num = 0
	bul = a[st]
	while num < n - 1:
		nx = next(st, n)
		bul += max(a[nx] - b[st], 0)
		st = nx
		num += 1
	print(min(ans, bul))
os.write(1, b'\n'.join(out))


import sys
import io, os

def main():
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
	t = int(input())
	for i in range(t):
		n = int(input())
		(game, dicta) = ([], [])
		for i in range(n):
			(a, b) = map(int, input().split())
			game.append(a)
			dicta.append(b)
		copy = game[:]
		for j in range(len(copy)):
			if j == 0:
				copy[0] = max(0, game[0] - dicta[-1])
			else:
				copy[j] = max(0, game[j] - dicta[j - 1])
		bullet = 100000000000000000000000000000000
		suma = sum(copy[1:])
		for k in range(n):
			if k > 0:
				suma -= copy[k]
				suma += copy[k - 1]
			bullets = game[k] + suma
			if bullets < bullet:
				bullet = bullets
		sys.stdout.write(str(bullet) + '\n')
main()


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	l1 = []
	l2 = []
	total = 0
	min_index = 10 ** 12 + 1
	min_prev = 10 ** 12 + 1
	(a1, b1) = map(int, input().split())
	l1.append(a1)
	l2.append(b1)
	for i in range(n):
		if i == 0:
			continue
		(a, b) = map(int, input().split())
		l1.append(a)
		l2.append(b)
		total += max(0, l1[i] - l2[i - 1])
		if min_index - max(0, min_index - min_prev) > l1[i] - max(0, l1[i] - l2[i - 1]):
			min_index = l1[i]
			min_prev = l2[i - 1]
	total += max(0, a1 - b)
	if min_index - max(0, min_index - min_prev) > l1[0] - max(0, l1[0] - l2[-1]):
		min_index = l1[0]
		min_prev = l2[-1]
	total += min_index - max(0, min_index - min_prev)
	sys.stdout.write(str(total) + '\n')


import sys
I = sys.stdin.buffer.readline
input = lambda : stdin.readline()
t = int(I())
while t > 0:
	n = int(I())
	add = 1000000000006
	ans = 0
	(a0, b0) = map(int, I().split())
	for i in range(n - 1):
		(a, b) = map(int, I().split())
		ans += max(0, a - b0)
		add = min(add, min(a, b0))
		b0 = b
	ans += max(0, a0 - b0)
	add = min(add, min(a0, b0))
	print(ans + add)
	t -= 1


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	n = int(input())
	monsters = [[int(i) for i in input().split()] for ___ in range(n)]
	extra_bullets = 0
	for ind in range(n):
		extra_bullets += max(0, monsters[ind][0] - monsters[ind - 1][1])
	minimum_bullets = float('inf')
	for ind in range(n):
		minimum_bullets = min(minimum_bullets, extra_bullets - max(0, monsters[ind][0] - monsters[ind - 1][1]) + monsters[ind][0])
	print(minimum_bullets)


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(a, b) = ([0] * n, [0] * n)
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
	(mini, minb) = (-1, 1e+18)
	for i in range(n):
		e = a[i] - max(0, a[i] - b[i - 1])
		if e < minb:
			mini = i
			minb = e
	res = a[mini]
	for i in range(1, n):
		res += max(0, a[(mini + i) % n] - b[(mini + i - 1) % n])
	print(res)


from sys import stdin, stdout
from collections import deque
R = lambda : stdin.readline().strip()
RL = lambda : list(map(int, R().split(' ')))
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
	n = int(input())
	bul = []
	damage = []
	for i in range(n):
		(a, b) = list(map(int, input().split()))
		bul.append(a)
		damage.append(b)
	req = []
	for i in range(n):
		if i == 0:
			req.append(max(0, bul[i] - damage[n - 1]))
		else:
			req.append(max(0, bul[i] - damage[i - 1]))
	total = sum(req)
	mi = bul[0] - req[0]
	for i in range(1, n):
		if bul[i] - req[i] < mi:
			mi = bul[i] - req[i]
	print(mi + total)


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

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		AB = [list(map(int, input().split())) for _ in range(n)]
		for (i, (a, b)) in enumerate(AB):
			a_prev = AB[(i + 1) % n][0]
			AB[i][1] = min(b, a_prev)
		ans = 0
		min_b = 10 ** 12 + 1
		for (a, b) in AB:
			ans += a
			ans -= b
			min_b = min(min_b, b)
		ans += min_b
		sys.stdout.write(str(ans) + '\n')
main()


import sys
input = sys.stdin.buffer.readline
t = int(input())
for qw in range(t):
	n = int(input())
	l1 = []
	l = []
	hoe = 0
	cc = 0
	pepe = 0
	iff = 0
	els = 0
	l2 = []
	counts = 0
	for i in range(n):
		(a, b) = map(int, input().split())
		l.append(a)
		if i != 0:
			count = bb - a
			if count < 0:
				l1.append(bb)
				iff = 1
				counts += a - bb
			else:
				l2.append(a)
				els = 1
		if i == 0:
			swag = a
			ver = b
		bb = b
		aa = a
	count = b - swag
	if count < 0:
		l1.append(b)
		iff = 1
		counts += swag - b
	else:
		l2.append(swag)
		els = 1
	if iff != 0 and els != 0:
		ww = min(l1)
		www = min(l2)
		if ww < www:
			ans = counts + ww
		else:
			ans = www + counts
	else:
		if iff == 0:
			www = min(l2)
			ans = www
		if els == 0:
			ww = min(l1)
			ans = ww + counts
	print(ans)


from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
ii = lambda : int(input())
lmii = lambda : list(map(int, input().split()))
slmii = lambda : sorted(map(int, input().split()))
li = lambda : list(input())
mii = lambda : map(int, input().split())
msi = lambda : map(str, input().split())

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

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

def main():
	for _ in ' ' * int(input()):
		(n, a, b) = (ii(), [], [])
		for i in range(n):
			(x, y) = mii()
			a.append(x)
			b.append(y)
		for i in range(n):
			b[i] = min(b[i], a[(i + 1) % n])
		print(sum(a) + min(b) - sum(b))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	(enemies, bombs, monsters) = ([], [], int(input()))
	for x in range(monsters):
		(a, b) = map(int, input().split())
		enemies.append(a)
		bombs.append(b)
	for j in range(monsters - 1):
		bombs[j] = min(bombs[j], enemies[j + 1])
	bombs[-1] = min(bombs[-1], enemies[0])
	print(sum(enemies) - sum(bombs) + min(bombs))


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	n = int(input())
	m = [list(map(int, input().split())) for i in range(n)]
	ans = 0
	for i in range(n):
		t = m[i][0] - m[i - 1][1]
		if t > 0:
			ans += t
			m[i][0] = m[i - 1][1]
	MIN = min(m)[0]
	print(ans + MIN)


import sys
input = sys.stdin.buffer.readline

def kot(a, b):
	if a > b:
		return a - b
	else:
		return 0

def sol():
	n = int(input())
	mon = [[0, 0]] * n
	for x in range(0, n):
		mon[x] = list(map(int, input().split()))
	a = mon[0][0]
	for x in range(1, n):
		if mon[x][0] - mon[x - 1][1] > 0:
			a += mon[x][0] - mon[x - 1][1]
		else:
			a += 0
	ans_a = a - (mon[0][0] - mon[1][0]) - kot(mon[1][0], mon[0][1]) + kot(mon[0][0], mon[n - 1][1])
	res = min(ans_a, a)
	for x in range(2, n):
		ans_a -= mon[x - 1][0] - mon[x][0] + kot(mon[x][0], mon[x - 1][1]) - kot(mon[x - 1][0], mon[x - 2][1])
		res = min(res, ans_a)
	return res
case = int(input())
for x in range(0, case):
	print(sol())


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
import sys, io, os
input = sys.stdin.readline
inf = float('inf')
mod = 10 ** 9 + 7

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

def yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b
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')
t = int(input())
for i in range(t):
	n = int(input())
	health = [0 for i in range(n)]
	dest = [0 for i in range(n)]
	for i in range(n):
		(health[i], dest[i]) = [int(i) for i in input().split()]
	a = health[:]
	for i in range(n - 1):
		a[i + 1] = max(a[i + 1] - dest[i], 0)
	dp = [0 for i in range(n)]
	dp[0] = sum(a)
	for i in range(n - 1):
		dp[i + 1] = dp[i] - health[i] + health[i + 1] + max(health[i] - dest[i - 1], 0) - max(health[i + 1] - dest[i], 0)
	print(min(dp))


import os
import sys
from io import BytesIO, IOBase
INF = 2 ** 62 - 1
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

def read_int():
	return int(input())

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

def slv(N, AB):
	abi = []
	for i in range(N):
		abi.append((max(0, AB[i][0] - AB[(i - 1) % N][1]), i))
	ans = INF
	offset = sum((a for (a, _) in abi))
	for i in range(N):
		ans = min(ans, offset + AB[i][0] - abi[i][0])
	return ans

def main():
	T = read_int()
	for _ in range(T):
		N = read_int()
		AB = [read_int_n() for _ in range(N)]
		print(slv(N, AB))
main()


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
	n = int(input())
	M = []
	mn = float('inf')
	bullets = 0
	(fa, fb) = map(int, input().split())
	(a1, b1) = (fa, fb)
	for _ in range(n - 1):
		(a2, b2) = map(int, input().split())
		bullets += max(0, a2 - b1)
		mn = min(mn, min(b1, a2))
		(a1, b1) = (a2, b2)
	(a2, b2) = (fa, fb)
	bullets += max(0, a2 - b1)
	mn = min(mn, min(b1, a2))
	bullets += mn
	print(bullets)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
T = int(input())
for tests in range(T):
	n = int(input())
	M = [list(map(int, input().split())) for i in range(n)]
	ANS = 0
	for i in range(n):
		if M[i][0] > M[i - 1][1]:
			ANS += M[i][0] - M[i - 1][1]
			M[i][0] = M[i - 1][1]
	MIN = M[0][0]
	for i in range(n):
		MIN = min(MIN, M[i][0])
	sys.stdout.write(str(ANS + MIN) + '\n')


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt
import math
from itertools import permutations

def main():
	for t in range(int(input())):
		n = int(input())
		a = []
		b = []
		v = [0] * n
		ans = 0
		r = 0
		for i in range(n):
			(x, y) = map(int, input().split())
			if r < x:
				ans += x - r
			v[i] = max(0, x - r)
			r = y
			a.append(x)
			b.append(y)
		mi = ans
		for i in range(n - 1):
			ans = ans - v[i] + max(0, a[i] - r) + a[(i + 1) % n] - v[(i + 1) % n]
			mi = min(mi, ans)
			v[(i + 1) % n] = a[(i + 1) % n]
			r = b[i]
		print(mi)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import sys
input = sys.stdin.buffer.readline
t = int(input())
while t:
	t -= 1
	n = int(input())
	arra = []
	arrb = []
	for i in range(n):
		(a, b) = [int(c) for c in input().split()]
		arra.append(a)
		arrb.append(b)
	for i in range(n - 1):
		arrb[i] = min(arrb[i], arra[i + 1])
	arrb[-1] = min(arrb[-1], arra[0])
	print(sum(arra) - sum(arrb) + min(arrb))


from sys import stdin
from sys import stdout
sprint = stdout.write
sinput = stdin.buffer.readline

def func():
	n = int(sinput())
	health = []
	exp = []
	for i in range(n):
		[h, e] = [int(x) for x in sinput().split()]
		health.append(h)
		exp.append(e)
	bullet = 0
	for i in range(n):
		te = max(0, health[i] - exp[i - 1])
		bullet += te
		health[i] -= te
	sprint('%d\n' % (bullet + min(health)))
t = int(sinput())
while t != 0:
	t -= 1
	func()


import sys

def main():
	res = ''
	input = sys.stdin.readline
	print = sys.stdout.write
	t = int(input())
	for _ in range(t):
		sub_res = 0
		n = int(input())
		(hp_f, boom_f) = map(int, input().split())
		boom_last = boom_f
		min_hp = hp_f
		for __ in range(n - 1):
			(hp, boom) = map(int, input().split())
			d = hp - boom_last
			if d > 0:
				sub_res += d
				hp -= d
			if hp < min_hp:
				min_hp = hp
			boom_last = boom
		(hp, boom) = (hp_f, boom_f)
		d = hp - boom_last
		if d > 0:
			sub_res += d
		if hp - d < min_hp:
			min_hp = hp - d
		sub_res += min_hp
		res += str(sub_res) + '\n'
	print(res)
main()


import os
import sys

def solve(A, B):
	cost = 0
	m = float('inf')
	for (idx, a) in enumerate(A):
		b = B[idx - 1]
		cost_add = max(a - b, 0)
		cost += cost_add
		m = min(m, a - cost_add)
	return cost + m

def pp(input):
	T = int(input())
	for i in range(T):
		n = int(input())
		(A, B) = zip(*(map(int, input().split(' ')) for _ in range(n)))
		print(solve(A, B))
if 'paalto' in os.getcwd():
	from string_source import string_source
	pp(string_source('1\n3\n7 15\n2 14\n5 3'))
else:
	input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
	pp(input)


from sys import stdin, stdout
t = int(stdin.readline())
res = []
for _ in range(t):
	n = int(stdin.readline())
	(a0, pb) = map(int, stdin.readline().split())
	s = 0
	weak = a0
	for _ in range(n - 1):
		(a, b) = map(int, stdin.readline().split())
		s += max(0, a - pb)
		weak = min(weak, a, pb)
		pb = b
	s += max(0, a0 - pb)
	res.append(str(s + min(weak, a0, pb)) + '\n')
stdout.writelines(res)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	a = [0 for i in range(n)]
	b = [0 for i in range(n)]
	res = 0
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
	first = 10 ** 15
	for i in range(1, n):
		res += max(0, a[i] - b[i - 1])
		first = min(first, min(a[i], b[i - 1]))
	res += max(0, a[0] - b[n - 1])
	first = min(first, min(a[0], b[n - 1]))
	print(res + first)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = []
	b = []
	for __ in range(n):
		(aa, bb) = [int(x) for x in input().split()]
		a.append(aa)
		b.append(bb)
	if n == 1:
		print(a[0])
		continue
	total = 0
	for i in range(n):
		if i == 0:
			bVal = b[n - 1]
		else:
			bVal = b[i - 1]
		total += max(a[i] - bVal, 0)
	ans = total - max(a[1] - b[0], 0) + a[1]
	for i in range(n):
		aVal = a[i]
		if i == 0:
			bVal = b[n - 1]
		else:
			bVal = b[i - 1]
		ans2 = total - max((aVal - bVal, 0)) + aVal
		ans = min(ans, ans2)
	print(ans)


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(a, b) = map(int, input().split())
	l = a
	z = 0
	su = 0
	t = b
	q = float('-infinity')
	for i in range(1, n):
		(a, b) = map(int, input().split())
		f = max(0, a - t)
		q = max(q, f - a)
		t = b
		su += f
	z = max(0, l - t)
	su += z
	q = max(q, z - l)
	print(su - q)


import sys
input = sys.stdin.buffer.readline
testCases = int(input())
for test in range(testCases):
	n = int(input())
	a = []
	b = []
	for i in range(n):
		(aa, bb) = map(int, input().split())
		a.append(aa)
		b.append(bb)
	ab = [0] * n
	for i in range(n):
		ab[i] = max(0, a[i] - b[i - 1])
	s = sum(ab)
	res = s - ab[0] + a[0]
	for i in range(1, n):
		if res > s - ab[i] + a[i]:
			res = s - ab[i] + a[i]
	print(res)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
	N = int(input())
	(a, b) = map(int, input().split())
	preb = b
	a0 = a
	mi = 10 ** 100
	s = 0
	for i in range(N - 1):
		(a, b) = map(int, input().split())
		mi = min(mi, a - max(0, a - preb))
		s += max(a - preb, 0)
		preb = b
	mi = min(mi, a0 - max(0, a0 - preb))
	s += max(a0 - preb, 0)
	print(mi + s)


import os
import sys
from io import BytesIO, IOBase

def Sol():
	n = int(input())
	hp = [0] * n
	damage = [0] * n
	res = [0] * n
	delta = [0] * n
	for i in range(n):
		(h, d) = map(int, input().split())
		hp[i] = h
		damage[i] = d
	res[0] = max(0, hp[0] - damage[-1])
	delta[0] = hp[0] - res[0]
	for i in range(1, n):
		res[i] = max(0, hp[i] - damage[i - 1])
		delta[i] = hp[i] - res[i]
	return sum(res) + min(delta)

def main():
	T = int(input())
	for _ in range(T):
		print(Sol())
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for i in range(t):
	n = int(input())
	a = [list(map(int, input().split())) for j in range(n)]
	c = 0
	for j in range(1, n):
		te = max(0, a[j][0] - a[j - 1][1])
		a[j].append(te)
		c = c + te
	a[0].append(max(0, a[0][0] - a[n - 1][1]))
	c = c + max(0, a[0][0] - a[n - 1][1])
	q = c - a[0][2] + a[0][0]
	for j in range(1, n):
		p = c - a[j][2] + a[j][0]
		q = min(p, q)
	print(q)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

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

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')

def main():
	for _ in range(N()):
		n = N()
		arr = []
		for _ in range(n):
			arr.append(list(RL()))
		rec = [0] * n
		for (i, v) in enumerate(arr):
			(a, _) = v
			rec[i] = max(a - arr[i - 1][1], 0)
		res = float('inf')
		sm = sum(rec)
		for i in range(n):
			now = sm + arr[i][0]
			if rec[i] != 0:
				now -= rec[i]
			res = min(res, now)
		print(res)
main()


import sys
input = sys.stdin.buffer.readline

def solve():
	n = int(input())
	if n == 0:
		return 0
	if n == 1:
		(a, b) = map(int, input().split())
		return a
	(a_first, b_first) = map(int, input().split())
	(a_prev, b_prev) = (a_first, b_first)
	remainder = float('inf')
	base_shots = 0
	for _ in range(n - 1):
		(a_curr, b_curr) = map(int, input().split())
		delta = a_curr - b_prev
		if delta > 0:
			base_shots += delta
			remainder = min(b_prev, remainder)
		else:
			remainder = min(a_curr, remainder)
		(a_prev, b_prev) = (a_curr, b_curr)
	(a_curr, b_curr) = (a_first, b_first)
	delta = a_curr - b_prev
	if delta > 0:
		base_shots += delta
		remainder = min(b_prev, remainder)
	else:
		remainder = min(a_curr, remainder)
	return base_shots + remainder
task_number = int(input())
solutions = [str(solve()) for _ in range(task_number)]
print('\n'.join(solutions))


import sys
input = sys.stdin.buffer.readline
t = int(input())
ans = []
for _ in range(t):
	n = int(input())
	a = []
	b = []
	for _ in range(n):
		(a_, b_) = map(int, input().split())
		a.append(a_)
		b.append(b_)
	cost = a[0]
	for i in range(n - 1):
		next_i = i + 1
		if b[i] < a[next_i]:
			cost += a[next_i] - b[i]
	pre_cost = cost
	for i in range(1, n):
		next_i = i + 1
		if next_i == n:
			next_i = 0
		pre_i = i - 1
		if pre_i == -1:
			pre_i = n - 1
		ppre_i = i - 2
		if ppre_i < 0:
			ppre_i %= n
		cur_cost = pre_cost - a[pre_i] - max(a[i] - b[pre_i], 0) + a[i] + max(a[pre_i] - b[ppre_i], 0)
		pre_cost = cur_cost
		cost = min(cost, cur_cost)
	ans.append(str(cost))
print('\n'.join(ans))


def main():
	import sys
	input = sys.stdin.buffer.readline
	mod = 998244353

	def GCD(x, y):
		while y:
			(x, y) = (y, x % y)
		return x

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

	def merge(a, start, mid, end, d):
		p = start
		q = mid + 1
		arr = [0] * (end - start + 1)
		k = 0
		coun = 0
		for i in range(start, end + 1):
			if p > mid:
				arr[k] = a[q]
				q += 1
				k += 1
			elif q > end:
				arr[k] = a[p]
				d[a[p]] += coun
				k += 1
				p += 1
			elif a[p] < a[q]:
				arr[k] = a[p]
				d[a[p]] += coun
				k += 1
				p += 1
			else:
				arr[k] = a[q]
				k += 1
				q += 1
				coun += 1
		for i in range(k):
			a[start] = arr[i]
			start += 1

	def mergesort(a, start, end, d):
		if start < end:
			mid = (start + end) // 2
			mergesort(a, start, mid, d)
			mergesort(a, mid + 1, end, d)
			merge(a, start, mid, end, d)

	def inversion(l):
		d = {}
		for i in l:
			d[i] = 0
		mergesort(l, 0, len(l) - 1, d)
		return d

	def binary_search_lower(A, low, high, k):
		if high - low != 1:
			mid = (low + high) // 2
			x = A[mid]
			if x >= k:
				return binary_search_lower(A, low, mid, k)
			else:
				return binary_search_lower(A, mid, high, k)
		if A[low] >= k:
			return low
		else:
			return high

	def binary_expo(x, n):
		if n == 0:
			return 1
		elif n % 2 == 0:
			return binary_expo(x * x, n // 2)
		else:
			return x * binary_expo(x * x, (n - 1) // 2)

	def modu_expo(x, n, m):
		if n == 0:
			return 1
		elif n % 2 == 0:
			return modu_expo(x * x % m, n // 2, m)
		else:
			return x * modu_expo(x * x % m, (n - 1) // 2, m) % m

	def eEuclid(c, m):
		if m == 0:
			global d
			global x
			global y
			d = c
			x = 1
			y = 0
		else:
			eEuclid(m, c % m)
			temp = x
			x = y
			y = temp - c // m * y

	def mod_Inv(c, m):
		eEuclid(c, m)
		return (x % m + m) % m

	def ncr(n, r, p):
		num = den = 1
		for i in range(r):
			num = num * (n - i) % p
			den = den * (i + 1) % p
		return num * pow(den, p - 2, p) % p
	for _ in range(int(input())):
		n = int(input())
		l = []
		for i in range(n):
			(a, b) = map(int, input().split())
			l.append([a, b])
		ans = 0
		for i in range(n - 1):
			if l[i][1] - l[i + 1][0] < 0:
				ans += l[i + 1][0] - l[i][1]
				l[i + 1][0] = l[i + 1][0] - (l[i + 1][0] - l[i][1])
		if l[-1][1] - l[0][0] < 0:
			ans += l[0][0] - l[-1][1]
			l[0][0] = l[0][0] - (l[0][0] - l[-1][1])
		min = 99999999999999
		for i in range(n):
			if l[i][0] < min:
				min = l[i][0]
		print(ans + min)
main()


import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
for _ in range(int(input())):
	n = int(input())
	a = []
	b = []
	for i in range(n):
		(aa, bb) = map(int, input().split())
		a.append(aa)
		b.append(bb)
	for i in range(n):
		if b[i - 1] >= a[i]:
			b[i - 1] = a[i]
	print(sum(a) - sum(b) + min(b))


import math, collections, sys
input = sys.stdin.buffer.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
T = int(input())
for i in range(T):
	N = int(input())
	a = []
	b = []
	for j in range(N):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	b[N - 1] = min(b[N - 1], a[0])
	for j in range(N - 1):
		b[j] = min(b[j], a[j + 1])
	s = sum(a) - sum(b) + min(b)
	print(s)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
cases = int(input())
for t in range(cases):
	n = int(input())
	ab = []
	for i in range(n):
		(a, b) = list(map(int, input().split()))
		ab.append([a, b])
	md = ab[1][0] - max(0, ab[1][0] - ab[0][1])
	st = 1
	for i in range(1, n):
		if md > ab[(i + 1) % n][0] - max(0, ab[(i + 1) % n][0] - ab[i][1]):
			st = (i + 1) % n
			md = ab[(i + 1) % n][0] - max(0, ab[(i + 1) % n][0] - ab[i][1])
	out = 0
	for i in range(n):
		p = (st + i) % n
		out += ab[p][0]
		ab[(p + 1) % n][0] = max(0, ab[(p + 1) % n][0] - ab[p][1])
	print(out)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, AB):
	cost = 0
	best = float('inf')
	for i in range(N):
		temp = max(0, AB[i][0] - AB[(i - 1) % N][1])
		cost += temp
		best = min(best, AB[i][0] - temp)
	return cost + best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N,) = [int(x) for x in input().split()]
	AB = [[int(x) for x in input().split()] for i in range(N)]
	ans = solve(N, AB)
	print(ans)


import sys
from itertools import islice
stdin = sys.stdin
T = int(stdin.readline())

def solve(arr):
	prev_exp = arr[-1][-1]
	bullets = 0
	mini = 1000000000000000000
	for (hp, exp) in arr:
		if hp > prev_exp:
			bullets += hp - prev_exp
		candidate = prev_exp if prev_exp < hp else hp
		if candidate < mini:
			mini = candidate
		prev_exp = exp
	return bullets + mini
for t in range(T):
	n = int(stdin.readline())
	monsters = [[int(y) for y in x.split()] for x in islice(stdin, n)]
	r = solve(monsters)
	print(r)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
t = int(input())
for _ in range(t):
	n = int(input())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	c = 0
	e = []
	for i in range(n):
		d = 0
		if a[i][1] < a[(i + 1) % n][0]:
			d = a[(i + 1) % n][0] - a[i][1]
			c += d
		e.append(a[(i + 1) % n][0] - d)
	sys.stdout.write(str(min(e) + c) + '\n')


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

def A():
	t = int(input())
	for _ in range(t):
		n = int(input())
		(p, c) = ([0] * n, [0] * n)
		succ = True
		for i in range(n):
			(p[i], c[i]) = map(int, input().split())
		if p[0] < c[0]:
			succ = False
		else:
			for i in range(1, n):
				if c[i] - c[i - 1] > p[i] - p[i - 1] or c[i] < c[i - 1] or p[i] < p[i - 1]:
					succ = False
					break
		if succ:
			print('YES')
		else:
			print('NO')
	return

def B():
	t = int(input())
	for _ in range(t):
		(n, x) = map(int, input().split())
		a = list(map(int, input().split()))
		a.sort(reverse=True)
		(tot, ppl) = (0, 0)
		for i in range(n):
			if a[i] + tot - x >= 0:
				ppl += 1
				tot += a[i] - x
			else:
				break
		print(ppl)
	return

def C():
	t = int(input())
	for _ in range(t):
		n = int(input())
		(a, b) = ([0] * n, [0] * n)
		c = [0] * n
		for i in range(n):
			(a[i], b[i]) = map(int, input().split())
		c[0] = max(0, a[0] - b[n - 1])
		s = c[0]
		for i in range(1, n):
			c[i] = max(0, a[i] - b[i - 1])
			s += c[i]
		m = a[0] - c[0]
		for i in range(1, n):
			if a[i] - c[i] < m:
				m = a[i] - c[i]
		print(s + m)
	return

def D():
	return
C()


import sys
input = sys.stdin.buffer.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def solve():
	N = getInt()
	sum_A = 0
	sum_B = 0
	min_B = 10 ** 15
	for n in range(N):
		(a, b) = getInts()
		if n > 0:
			y = min(a, prev_b)
			sum_B += y
			min_B = min(min_B, y)
		else:
			first_a = a
		sum_A += a
		prev_b = b
	y = min(first_a, prev_b)
	sum_B += y
	min_B = min(min_B, y)
	return sum_A - sum_B + min_B
T = getInt()
for t in range(T):
	print(solve())


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	ar = []
	br = []
	for i in range(n):
		(a, b) = map(int, input().split())
		ar.append(a)
		br.append(b)
	ans = 0
	for i in range(n):
		if ar[i] > br[i - 1]:
			ans += ar[i] - br[i - 1]
			ar[i] = br[i - 1]
	ans += min(ar)
	print(ans)


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')
t = int(input())
for _ in range(t):
	n = int(input())
	prev = -1
	tot = 0
	mn = 1145141919810
	for ni in range(n):
		(a, b) = map(int, input().split(' '))
		if ni != 0:
			if a - prev >= 0:
				tot += a - prev
				tmp = a - prev
			else:
				tmp = 0
			if a - tmp < mn:
				mn = a - tmp
		else:
			blood0 = a
		prev = b
	if blood0 - prev >= 0:
		tot += blood0 - prev
		tmp = blood0 - prev
	else:
		tmp = 0
	if blood0 - tmp < mn:
		mn = blood0 - tmp
	print(mn + tot)


from sys import stdin, stdout
input = stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = []
	b = []
	for __ in range(n):
		(x, y) = list(map(int, input().split()))
		a.append(x)
		b.append(y)
	sm = max(0, a[0] - b[-1])
	a[0] -= max(0, a[0] - b[-1])
	for i in range(1, n):
		sm += max(0, a[i] - b[i - 1])
		a[i] -= max(0, a[i] - b[i - 1])
	stdout.write(str(sm + min(a)) + '\n')


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = []
	b = []
	for __ in range(n):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	suma = 0
	for i in range(n):
		suma += max(a[i] - b[(i - 1) % n], 0)
	mini = a[0] + suma - max(a[0] - b[-1 % n], 0)
	for i in range(n):
		mini = min(mini, a[i] + suma - max(a[i] - b[(i - 1) % n], 0))
	print(mini)


import sys
input = sys.stdin.buffer.readline

def solve(n, arr):
	total = 0
	for i in range(n - 1):
		total += max(arr[i + 1][0] - arr[i][1], 0)
	total += max(arr[0][0] - arr[n - 1][1], 0)
	minv = float('inf')
	for i in range(1, n):
		t = arr[i][0] - max(arr[i][0] - arr[i - 1][1], 0) + total
		minv = min(minv, t)
	minv = min(minv, arr[0][0] - max(arr[0][0] - arr[n - 1][1], 0) + total)
	return minv
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [[int(el) for el in input().split()] for i in range(n)]
	ans = solve(n, arr)
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	n = int(input())
	mark = []
	Ans = []
	jaya = []
	for i in range(n):
		(a, b) = map(int, input().split())
		mark.append((a, b))
	for i in range(n):
		if mark[i][1] - mark[(i + 1) % n][0] >= 0:
			Ans.append(0)
		elif mark[i][1] - mark[(i + 1) % n][0] < 0:
			Ans.append(abs(mark[i][1] - mark[(i + 1) % n][0]))
	t = sum(Ans[:n - 1])
	Ans += Ans
	for i in range(n):
		jaya.append(mark[i][0] + t)
		t -= Ans[i]
		t += Ans[i + n - 1]
	print(min(jaya))


import os, sys
input = sys.stdin.buffer.read().split(b'\n')[::-1].pop
T = int(input())
ans = []
for tt in range(T):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		(x, y) = [int(x) for x in input().split()]
		a.append(x)
		b.append(y)
	minv = 4557430888798830399
	total = 0
	for i in range(n):
		j = i - 1 if i > 0 else n - 1
		total += max(0, a[i] - b[j])
		minv = min(minv, a[i], b[j])
	ans.append(str(total + minv).encode())
os.write(1, '\n'.encode().join(ans))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def solve():
	n = int(input().strip())
	(A, B) = ([], [])
	for _ in range(n):
		(a, b) = [int(s) for s in input().strip().split()]
		A.append(a)
		B.append(b)
	left = [max(A[i] - B[(i - 1) % n], 0) for i in range(n)]
	s = sum(left)
	result = min((A[i] + s - left[i] for i in range(n)))
	print(result)

def main():
	for _ in range(int(input().strip())):
		solve()
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
I = sys.stdin.buffer.readline
for _ in range(int(I())):
	n = int(I())
	a = []
	b = []
	c = [0]
	sumi = 0
	ans = int(1e+17)
	for i in range(n):
		(ai, bi) = map(int, I().split())
		a.append(ai)
		b.append(bi)
		if i != 0:
			c.append(max(0, a[i] - b[(i - 1) % n]))
			sumi += c[i]
			ans = min(a[i] - c[i], ans)
	c[0] = max(0, a[0] - b[n - 1])
	sumi += c[0]
	ans = min(a[0] - c[0], ans)
	print(ans + sumi)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(a, b, d, s_d) = ([0] * n, [0] * n, [0] * n, 0)
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
		d[i] = a[i] if i == 0 else max(0, a[i] - b[i - 1])
		s_d += d[i]
	(ans, s_m) = (s_d, s_d - a[0] + max(0, a[0] - b[-1]))
	for i in range(1, n):
		ans = min(ans, s_m - d[i] + a[i])
	print(ans)


import sys
input = sys.stdin.buffer.readline

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		A = [0] * n
		B = [0] * n
		for i in range(n):
			(a, b) = map(int, input().split())
			A[i] = a
			B[i] = b
		R = [0] * n
		for i in range(n):
			if i != 0:
				if A[i] - B[i - 1] < 0:
					R[i] = 0
				else:
					R[i] = A[i] - B[i - 1]
			elif A[i] - B[n - 1] < 0:
				R[i] = 0
			else:
				R[i] = A[i] - B[n - 1]
		s = sum(R)
		ans = 10 ** 19
		for i in range(n):
			if ans >= s - R[i] + A[i]:
				ans = s - R[i] + A[i]
		print(ans)
main()


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
from math import sqrt, floor, factorial, gcd
from collections import deque, Counter, defaultdict
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))
from collections import deque
input = lambda : sys.stdin.readline().rstrip('\r\n')
read = lambda : list(map(int, input().split(' ')))

def solve():
	for _ in range(int(input())):
		n = int(input())
		arr = []
		for i in range(n):
			arr.append(read())
		b_arr = [0] * n
		s = 0
		for i in range(n):
			b_arr[i] = max(0, arr[i][0] - arr[(i - 1) % n][1])
			s += max(0, arr[i][0] - arr[(i - 1) % n][1])
		ans = float('inf')
		for i in range(n):
			ans = min(ans, arr[i][0] + (s - b_arr[i]))
		print(ans)
solve()


def main():
	import sys
	input = sys.stdin.buffer.readline
	for _ in range(int(input())):
		n = int(input())
		l = []
		for i in range(n):
			(a, b) = map(int, input().split())
			l.append([a, b])
		ans = 0
		for i in range(n - 1):
			if l[i][1] - l[i + 1][0] < 0:
				ans += l[i + 1][0] - l[i][1]
				l[i + 1][0] = l[i + 1][0] - (l[i + 1][0] - l[i][1])
		if l[-1][1] - l[0][0] < 0:
			ans += l[0][0] - l[-1][1]
			l[0][0] = l[0][0] - (l[0][0] - l[-1][1])
		min = 99999999999999
		for i in range(n):
			if l[i][0] < min:
				min = l[i][0]
		print(ans + min)
main()


import sys
I = sys.stdin.buffer.readline
input = lambda : stdin.readline()
for _ in range(int(I())):
	n = int(I())
	(ans, mn) = (0, 100000000000000)
	(ai, bi) = map(int, I().split())
	for i in range(n - 1):
		(na, nb) = map(int, I().split())
		if na > bi:
			ans += na - bi
			mn = min(mn, bi)
		else:
			mn = min(mn, na)
		bi = nb
	if ai > bi:
		ans += ai - bi
		mn = min(mn, bi)
	else:
		mn = min(mn, ai)
	print(ans + mn)


import sys
input = sys.stdin.buffer.readline

def main():
	t = int(input())
	ans = [0] * t
	for j in range(t):
		n = int(input())
		l = [list(map(int, input().split())) for _ in range(n)]
		s = 0
		m = 100000000000000.0
		fb = l[-1][-1]
		for (a, b) in l:
			t = max(0, a - fb)
			s += t
			if a - t < m:
				m = a - t
			fb = b
		ans[j] = s + m
	print('\n'.join(map(str, ans)))
main()


import sys
from os import path
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = []
	b = []
	for i in range(n):
		(_a, _b) = map(int, input().split())
		a.append(_a)
		b.append(_b)
	extra = 0
	for i in range(n):
		next = (i + 1) % n
		extra += max(0, a[next] - b[i])
	ans = float('inf')
	for i in range(n):
		prev = i - 1
		if prev < 0:
			prev += n
		ans = min(ans, extra + a[i] - max(0, a[i] - b[prev]))
	print(ans)


import sys
input = sys.stdin.buffer.readline
t = int(input())
while t:
	t -= 1
	n = int(input())
	x = []
	y = []
	for i in range(n):
		(a, b) = map(int, input().split())
		x.append(a)
		y.append(b)
	count = 0
	for i in range(n):
		if x[i] - y[i - 1] > 0:
			count += x[i] - y[i - 1]
			x[i] = y[i - 1]
	ans = min(x)
	print(count + ans)


from sys import stdin, stdout
t = int(stdin.readline())
ans = []
for s in range(t):
	n = int(stdin.readline())
	(least, bs) = map(int, stdin.readline().split())
	start = least
	total = 0
	for i in range(n - 1):
		(a, b) = map(int, stdin.readline().split())
		least = min(least, a, bs)
		total += max(0, a - bs)
		bs = b
	total += max(0, start - bs)
	ans.append(str(total + min(least, start, bs)) + '\n')
stdout.writelines(ans)


from sys import stdin, gettrace

def input():
	return stdin.buffer.readline()

def main():

	def solve():
		n = int(input())
		aa = []
		bb = []
		mins = int(100000000000000.0)
		sum = 0
		for i in range(n):
			(a, b) = map(int, input().split())
			aa.append(a)
			bb.append(b)
		for i in range(n):
			sum += max(0, aa[i] - bb[(i - 1) % n])
		for i in range(n):
			mins = min(aa[i], bb[(i - 1) % n], mins)
		print(sum + mins)
	q = int(input())
	for _ in range(q):
		solve()
main()


import os
import sys
from io import BytesIO, IOBase

def main():

	def next(st, n):
		if st == n - 1:
			return 0
		return st + 1
	for t in range(int(input().strip())):
		n = int(input().strip())
		a = []
		b = []
		for i in range(n):
			(x, y) = [int(j) for j in input().split()]
			a.append(x)
			b.append(y)
		if n == 1:
			print(a[0])
			continue
		m = []
		for i in range(n):
			m.append((b[i - 1], a[i], i))
		st = min(m)[2]
		num = 0
		bul = a[st]
		while num < n - 1:
			nx = next(st, n)
			bul += max(a[nx] - b[st], 0)
			st = nx
			num += 1
		ans = bul
		m = []
		for i in range(n):
			m.append((a[i], b[i - 1], i))
		st = min(m)[2]
		num = 0
		bul = a[st]
		while num < n - 1:
			nx = next(st, n)
			bul += max(a[nx] - b[st], 0)
			st = nx
			num += 1
		print(str(min(ans, bul)))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import sys
input = sys.stdin.buffer.readline
t = int(input())
for i in range(t):
	n = int(input())
	a = []
	b = []
	for j in range(n):
		(a_, b_) = [int(s) for s in input().split()]
		a.append(a_)
		b.append(b_)
	min_ = 1000000000000
	if b[-1] < a[0]:
		ans = a[0] - b[-1]
		a[0] = b[-1]
	else:
		ans = 0
	if a[0] < min_:
		min_ = a[0]
	for j in range(len(a) - 1):
		if b[j] < a[j + 1]:
			ans += a[j + 1] - b[j]
			a[j + 1] = b[j]
		if a[j + 1] < min_:
			min_ = a[j + 1]
	print(ans + min_)


from sys import stdin, stdout
t = int(stdin.readline())
res = []
for _ in range(t):
	n = int(stdin.readline())
	(a0, prevb) = map(int, stdin.readline().split())
	(ans, mn) = (0, a0)
	for _ in range(n - 1):
		(a, b) = map(int, stdin.readline().split())
		ans += max(0, a - prevb)
		mn = min(mn, a, prevb)
		prevb = b
	ans += max(0, a0 - prevb)
	res.append(str(ans + min(mn, prevb)) + '\n')
stdout.writelines(res)


import sys
input = sys.stdin.buffer.readline
T = int(input())
for t in range(T):
	n = int(input())
	hp = []
	bomb = []
	bomb.append(0)
	for i in range(n):
		(x, y) = map(int, input().split())
		hp.append(x)
		bomb.append(y)
	bomb[0] = bomb.pop(-1)
	for i in range(n):
		bomb[i] = min(bomb[i], hp[i])
	print(sum(hp) - sum(bomb) + min(bomb))


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.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(io.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()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
T = int(input())
Ans = [0] * T
for idx_testcase in range(T):
	N = int(input())
	AB = [list(map(int, input().split())) for _ in range(N)]
	(A, B) = map(list, zip(*AB))
	A_ = A[:]
	A_[0] = max(A_[0] - B[-1], 0)
	for (i, b) in enumerate(B[:-1], 1):
		A_[i] -= b
		if A_[i] < 0:
			A_[i] = 0
	ans = sum(A_)
	mi = 1 << 60
	for (a, a_) in zip(A, A_):
		if mi > a - a_:
			mi = a - a_
	ans += mi
	Ans[idx_testcase] = ans
print('\n'.join(map(str, Ans)))


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')
testcases = int(input())
for j in range(testcases):
	n = int(input())
	hel = []
	exp = []
	for b in range(n):
		vals = list(map(int, input().split()))
		hel.append(vals[0])
		exp.append(vals[1])
	afex = []
	for k in range(n):
		if k == 0:
			afex.append(hel[0] - exp[-1])
		else:
			afex.append(hel[k] - exp[k - 1])
	lowerb = 0
	for s in range(len(afex)):
		if afex[s] > 0:
			lowerb += abs(afex[s])
			hel[s] += -abs(afex[s])
	print(lowerb + min(min(exp), min(hel)))


import os
import sys
from io import BytesIO, IOBase

def iin():
	return int(input())

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

def main():
	T = iin()
	while T:
		T -= 1
		n = iin()
		(a1, a2) = ([], [])
		for i in range(n):
			(j, k) = lin()
			a1.append(j)
			a2.append(k)
		ans = 0
		if n == 1:
			ans = a1[0]
		else:
			for i in range(n):
				a2[i] = min(a2[i], a1[(i + 1) % n])
			if n == 2:
				ans = min(a1[0] + a1[1] - a2[0], a1[1] + a1[0] - a2[1])
			else:
				sm = 0
				x = a2[-1]
				a2[-1] = 0
				for i in range(n - 1, -1, -1):
					sm += a1[i] - a2[i - 1]
				a2[-1] = x
				ans = sm
				for i in range(1, n):
					(x1, x2) = (i - 2, i - 1)
					sm = sm + a2[x2] - a2[x1]
					ans = min(sm, ans)
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from sys import stdin, stdout
result = []
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	(a1, pb) = map(int, stdin.readline().split())
	(s, m) = (0, a1)
	for _ in range(n - 1):
		(a, b) = map(int, stdin.readline().split())
		s += max(0, a - pb)
		m = min(m, a, pb)
		pb = b
	s += max(0, a1 - pb)
	result.append(str(s + min(m, a1, pb)) + '\n')
stdout.writelines(result)


import sys
import os
import io
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
import math

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def si():
	return input()
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

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

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def li():
	return list(map(int, input().split()))
t = int(input())
for _ in range(t):
	n = ii()
	l = []
	for i in range(n):
		l.append(li())
	prev = l[0][0]
	for i in range(n - 1):
		prev += max(0, l[i + 1][0] - l[i][1])
	m = prev
	for i in range(0, n - 1):
		prev = prev - l[i][0]
		if l[i + 1][0] < l[i][1]:
			prev += l[i + 1][0]
		else:
			prev += l[i][1]
		prev += max(0, l[i][0] - l[(i - 1) % n][1])
		m = min(m, prev)
	print(m)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	prox = lambda x, y: (x + 1) % y
	test = int(input())
	while test:
		n = int(input())
		monster = []
		minimum_s = 0
		for i in range(n):
			monster.append(list(map(int, input().split())))
		for i in range(n):
			minimum_s += max(0, monster[prox(i, n)][0] - monster[i][1])
		ans = minimum_s + monster[0][0]
		for mon in monster:
			if mon[0] > mon[1]:
				ans = min(ans, minimum_s + mon[1])
			else:
				ans = min(ans, minimum_s + mon[0])
		print(ans)
		test -= 1
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
(input, print) = (sys.stdin.buffer.readline, sys.stdout.write)
for _ in range(int(input())):
	n = int(input())
	(a1, b1) = map(int, input().split())
	(a, b) = ([a1], [0])
	s = 0
	for _ in range(n - 1):
		(a2, b2) = map(int, input().split())
		a.append(a2)
		b.append(max(a2 - b1, 0))
		(a1, b1) = (a2, b2)
		s += b[-1]
	b[0] = max(a[0] - b1, 0)
	s += b[0]
	print(str(min([s + a[i] - b[i] for i in range(n)])) + '\n')


import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
T = int(input())
for _ in range(T):
	N = int(input())
	(a, b) = map(int, input().split())
	preb = b
	a0 = a
	mi = 10 ** 100
	s = 0
	for i in range(N - 1):
		(a, b) = map(int, input().split())
		mi = min(mi, a - max(0, a - preb))
		s += max(a - preb, 0)
		preb = b
	mi = min(mi, a0 - max(0, a0 - preb))
	s += max(a0 - preb, 0)
	print(mi + s)


import sys
input = sys.stdin.buffer.readline

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

def sieve(n):
	a = [1] * n
	for i in range(2, n):
		if a[i]:
			for j in range(i * i, n, i):
				a[j] = 0
	return a
for __ in range(int(input())):
	n = int(input())
	s = 0
	a = [0] * n
	b = [0] * n
	extraForStart = 10000000000000
	for i in range(n):
		(a[i], b[i]) = I()
	for i in range(n):
		s += max(0, a[i] - b[i - 1])
		extraForStart = min(extraForStart, a[i] - max(0, a[i] - b[i - 1]))
	print(s + extraForStart)


import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
t = int(input())
for i in range(t):
	n = int(input())
	a = []
	b = []
	for j in range(n):
		(p, q) = map(int, input().split())
		a.append(p)
		b.append(q)
	s = 0
	m = 1000000000000000000000
	for j in range(n):
		s += max(0, a[j] - b[j - 1])
		m = min(a[j], b[j - 1], m)
	print(s + m)


import os, sys
pos = 0
inp = os.read(0, int(10000000.0)).split()
T = int(inp[pos])
pos += 1
ans = [None for i in range(T)]
tt = 0
while tt < T:
	n = int(inp[pos])
	pos += 1
	i = 0
	minv = 4557430888798830399
	total = 0
	while i < n:
		a = int(inp[pos])
		pos += 1
		b = int(inp[pos])
		pos += 1
		if i == 0:
			firsta = a
		else:
			total += max(0, a - pb)
		minv = min(minv, a, b)
		pb = b
		i += 1
	total += max(0, firsta - b)
	ans[tt] = str(total + minv).encode()
	tt += 1
os.write(1, '\n'.encode().join(ans))


import sys
input = sys.stdin.buffer.readline

def solution():
	n = int(input())
	a = []
	m = 1e+18
	b = []
	ans = 0
	for i in range(n):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	for i in range(n):
		z = (i + 1) % n
		val = min(a[z], b[i])
		ans += a[z] - val
		m = min(m, val)
	ans += m
	print(ans)
for _ in range(int(input())):
	solution()


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	count = 0
	a = [0] * n
	b = [0] * n
	minimum = 10 ** 12 + 1
	for l in range(n):
		(a[l], b[l]) = map(int, input().split())
	for i in range(n):
		if a[i] - b[i - 1] > 0:
			count += a[i] - b[i - 1]
			minimum = min(minimum, b[i - 1])
		else:
			minimum = min(minimum, a[i])
	count += minimum
	print(count)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	n = int(input())
	arr = [list(map(int, input().split())) for i in range(n)]
	add = 0
	x = arr[0][0] - arr[-1][1]
	base = x if x > 0 else 0
	add = arr[0][0] - x if x > 0 else arr[0][0]
	for i in range(1, n):
		k = arr[i][0] - arr[i - 1][1]
		if k > 0:
			base += k
			add = min(add, arr[i][0] - k)
		else:
			add = min(add, arr[i][0])
	print(base + add)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for f in range(t):
	n = int(input())
	a = [0] * n
	b = [0] * n
	s1 = 0
	s2 = 0
	s3 = 100000000000000000
	c = [0] * n
	b[-1] = s3
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
		s1 += a[i]
		c[i] = min(a[i], b[i - 1])
		s3 = min(s3, c[i])
		s2 += c[i]
	c[0] = min(a[0], b[-1])
	s3 = min(s3, c[0])
	s2 -= a[0]
	s2 += c[0]
	print(s3 + s1 - s2)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for qw in range(t):
	n = int(input())
	cc = 0
	pepe = 0
	iff = 0
	els = 0
	counts = 0
	for i in range(n):
		(a, b) = map(int, input().split())
		if i != 0:
			count = bb - a
			if count < 0:
				if cc == 0:
					crow = bb
					cc = 1
				elif crow > bb:
					crow = bb
				iff = 1
				counts += a - bb
			else:
				if pepe == 0:
					hoe = a
					pepe = 1
				elif hoe > a:
					hoe = a
				els = 1
		if i == 0:
			swag = a
			ver = b
		bb = b
		aa = a
	count = b - swag
	if count < 0:
		if cc == 0:
			crow = b
			cc = 1
		elif crow > bb:
			crow = b
		iff = 1
		counts += swag - b
	else:
		if pepe == 0:
			hoe = swag
			pepe = 1
		elif hoe > swag:
			hoe = swag
		els = 1
	if iff != 0 and els != 0:
		if crow < hoe:
			ans = counts + crow
		else:
			ans = hoe + counts
	else:
		if iff == 0:
			ans = hoe
		if els == 0:
			ww = crow
			ans = ww + counts
	print(ans)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	arr = []
	ans = 0
	m = 10 ** 20
	for i in range(n):
		arr.append(list(map(int, input().split())))
		if i > 0:
			k = max(0, arr[i][0] - arr[i - 1][1])
			ans += k
			m = min(m, arr[i][0] - k)
	k = max(0, arr[0][0] - arr[n - 1][1])
	ans += k
	m = min(m, arr[0][0] - k)
	ans += m
	print(ans)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	(n, best, best_i) = (int(input()), float('inf'), -1)
	vals = [[int(i) for i in input().split()] for j in range(n)]
	vals.append(vals[0])
	for i in range(n):
		if vals[i + 1][0] - max(0, vals[i + 1][0] - vals[i][1]) < best:
			best = vals[i + 1][0] - max(0, vals[i + 1][0] - vals[i][1])
			best_i = i + 1
	(new_vals, ans) = ([vals[(best_i + i) % n] for i in range(n)], 0)
	for i in range(n - 1):
		ans += max(new_vals[i][0], 0)
		new_vals[i + 1][0] -= new_vals[i][1]
	ans += max(new_vals[-1][0], 0)
	print(ans)


import os
import sys
import math
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')
a = int(input())
for i in range(a):
	s = int(input())
	ans = []
	gan = []
	total = 0
	mini = math.inf
	flag = 0
	tan = [0 for i in range(s)]
	for i in range(s):
		(x, y) = map(int, input().split())
		ans.append([x, y])
		gan.append([x, y])
		mini = min(x, mini)
	for i in range(1, len(ans)):
		ans[i][0] = ans[i][0] - ans[i - 1][1]
		if ans[i][0] >= 0:
			total += max(0, ans[i][0])
	ans[0][0] = ans[0][0] - ans[-1][1]
	total += max(0, ans[0][0])
	for i in range(len(ans)):
		mini = min(gan[i][0] - max(0, ans[i][0]), mini)
	total += mini
	print(total)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for k in range(t):
	n = int(input())
	a = [[int(el) for el in input().split()] for i in range(n)]
	s = 0
	for i in range(n):
		s += max(0, a[i][0] - a[i - 1][1])
	m = 10 ** 20
	for i in range(n):
		m = min(m, s + a[i][0] - max(0, a[i][0] - a[i - 1][1]))
	print(m)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
for _ in range(int(input())):
	n = int(input())
	m = [list(map(int, input().split())) for i in range(n)]
	ans = 0
	for i in range(n):
		t = m[i][0] - m[i - 1][1]
		if t > 0:
			ans += t
			m[i][0] = m[i - 1][1]
	MIN = min(m)[0]
	sys.stdout.write(str(ans + MIN) + '\n')


import sys
input = sys.stdin.buffer.readline
nn = int(input())
for tc in range(nn):
	n = int(input())
	M = [list(map(int, input().split())) for i in range(n)]
	ans = 0
	for i in range(n):
		if M[i][0] > M[i - 1][1]:
			ans += M[i][0] - M[i - 1][1]
			M[i][0] = M[i - 1][1]
	MIN = M[0][0]
	for i in range(n):
		MIN = min(MIN, M[i][0])
	print(ans + MIN)


import sys
input = sys.stdin.buffer.readline

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	while x != link[x]:
		x = link[x]
	return x

def union(x, y, size, link):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

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

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	n = int(input())
	a = []
	b = []
	for __ in range(n):
		(x, y) = int_array()
		a.append(x)
		b.append(y)
	that = [None] * n
	that[0] = max(0, a[0] - b[-1])
	for i in range(1, n):
		that[i] = max(0, a[i] - b[i - 1])
	var = sum(that[:n])
	ans = INF
	for i in range(n):
		var -= that[i]
		cost = var + a[i]
		var += that[i]
		ans = min(ans, cost)
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
	n = int(input())
	M = []
	for _ in range(n):
		(a, b) = map(int, input().split())
		M.append((a, b))
	mn = float('inf')
	bullets = 0
	for (i, m) in enumerate(M):
		(a1, b1) = m
		(a2, b2) = M[(i + 1) % n]
		bullets += max(0, a2 - b1)
		mn = min(mn, min(b1, a2))
	bullets += mn
	print(bullets)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(h, d) = ([0] * n, [0] * n)
	for i in range(n):
		(x, y) = map(int, input().split())
		(h[i], d[i]) = (x, y)
	for i in range(n - 1):
		d[i] = min(d[i], h[i + 1])
	d[-1] = min(d[-1], h[0])
	print(sum(h) - sum(d) + min(d))


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = []
	b = []
	for i in range(0, n):
		(ai, bi) = list(map(int, input().split()))
		a.append(ai)
		b.append(bi)
	extra = []
	for i in range(0, n):
		extra.append(max(0, a[i] - b[(i - 1) % n]))
	T = sum(extra)
	c = []
	for i in range(0, n):
		c.append(T - extra[i] + a[i])
	print(min(c))


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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 value():
	return tuple(map(int, input().split()))

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

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	a = []
	for i in range(n):
		a.append(value())
	bullets = a[0][0]
	for i in range(1, n):
		bullets += max(0, a[i][0] - a[i - 1][1])
	ans = bullets
	for i in range(1, n):
		bullets += a[i][0]
		bullets -= max(0, a[i][0] - a[i - 1][1])
		prev = a[i - 1]
		prev2 = a[i - 2]
		if i - 2 < 0:
			prev2 = a[-1]
		bullets -= prev[0]
		bullets += max(0, prev[0] - prev2[1])
		ans = min(bullets, ans)
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [0] * n
	b = [0] * n
	c = [0] * n
	for i in range(n):
		(a[i], b[i]) = map(int, input().split())
		if i > 0:
			c[i] = max(a[i] - b[i - 1], 0)
	c[0] = max(a[0] - b[-1], 0)
	ss = sum(c)
	ans = ss - c[0] + a[0]
	for i in range(1, n):
		ans = min(ans, ss - c[i] + a[i])
	print(ans)


import sys
input = sys.stdin.buffer.readline

def gift():
	for _ in range(t):
		n = int(input())
		inamo = []
		for i in range(n):
			mosnteri = list(map(int, input().split()))
			inamo.append(mosnteri)
		dingding = [max(inamo[0][0] - inamo[n - 1][1], 0)]
		biu = dingding[0]
		for i in range(n - 1):
			curr = inamo[i][1]
			nexmon = inamo[i + 1][0]
			temp = max(nexmon - curr, 0)
			biu += temp
			dingding.append(temp)
		jojo = float('inf')
		for i in range(n):
			jojo = min(jojo, inamo[i][0] + biu - dingding[i])
		yield jojo
t = int(input())
ans = gift()
print(*ans, sep='\n')


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
for u in range(int(input())):
	n = int(input())
	(l, d) = ([], [])
	for i in range(n):
		(a, b) = map(int, input().split())
		l.append(a)
		d.append(b)
	s = 0
	for i in range(n):
		if l[i] > d[i - 1]:
			s = s + (l[i] - d[i - 1])
			l[i] = d[i - 1]
	s = s + min(l)
	print(s)


import sys

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

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

def JA(a, sep):
	return sep.join(map(str, a))

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		ab = [LI() for _ in range(n)]
		r = 0
		t = 10 ** 12
		for i in range(n):
			a = ab[i][0]
			k = max(a - ab[i - 1][1], 0)
			r += k
			if t > a - k:
				t = a - k
		rr.append(r + t)
	return JA(rr, '\n')
print(main())


def main_function():
	import io
	import os
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
	import sys
	for _ in range(int(input())):
		n = int(input())
		memo = [list(map(int, input().split())) for i in range(n)]
		total_damage_with_explosion = 0
		for i in range(n):
			if memo[i][0] > memo[i - 1][1]:
				total_damage_with_explosion += memo[i][0] - memo[i - 1][1]
		ans = float('inf')
		for i in range(n):
			if memo[i][0] > memo[i - 1][1]:
				ans = min(ans, total_damage_with_explosion + memo[i - 1][1])
			else:
				ans = min(ans, total_damage_with_explosion + memo[i][0])
		sys.stdout.write(str(ans) + '\n')
main_function()


from sys import stdin
case = int(stdin.buffer.readline())
for iiiiiiiii in range(case):
	n = int(stdin.buffer.readline())
	a = [0] * n
	b = [0] * n
	c = [0] * n
	c_all = 0
	ans = float('inf')
	for i in range(n):
		s = stdin.buffer.readline().split()
		a[i] = int(s[0])
		b[i] = int(s[1])
	for i in range(n):
		damage = a[i] - b[i - 1] if i > 0 else a[i] - b[-1]
		if damage < 0:
			damage = 0
		c[i] = damage
		c_all += damage
	for i in range(n):
		bullet = c_all + a[i] - c[i]
		if bullet < ans:
			ans = bullet
	print(ans)


from sys import stdin
import bisect
import heapq
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 iin():
	return int(input())

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

def main():
	return map(int, input().split())
for _ in range(int(input())):
	n = iin()
	(a, b) = main()
	l = a
	z = 0
	su = 0
	t = b
	q = float('-infinity')
	for i in range(1, n):
		(a, b) = main()
		f = max(0, a - t)
		q = max(q, f - a)
		t = b
		su += f
	z = max(0, l - t)
	su += z
	q = max(q, z - l)
	print(su - q)


import sys
input = sys.stdin.buffer.readline
tests = int(input())
for ii in range(tests):
	n = int(input())
	a = []
	b = []
	for i in range(1, n + 1):
		(x, y) = map(int, input().split())
		a.append(x)
		b.append(y)
	sum = 0
	a.append(a[0])
	b.append(b[0])
	for i in range(1, n + 1):
		sum += max(a[i] - b[i - 1], 0)
	ans = sum + a[1]
	for i in range(1, n + 1):
		val = max(a[i] - b[i - 1], 0)
		ans = min(ans, sum + a[i] - val)
	print(ans)


from sys import stdin
t = int(stdin.buffer.readline())
for _ in range(t):
	n = int(stdin.buffer.readline())
	a = list()
	b = list()
	for _ in range(n):
		(x, y) = map(int, stdin.buffer.readline().split())
		a.append(x)
		b.append(y)
	Sum = 0
	res = float('inf')
	for i in range(n):
		d = a[i] - b[(i - 1 + n) % n] if a[i] >= b[(i - 1 + n) % n] else 0
		Sum += d
		res = min(res, a[i] - d)
	print(Sum + res)


from sys import stdout, stdin
input = stdin.buffer.readline
t = int(input())
for z in range(t):
	n = int(input())
	health = []
	explosion = []
	for i in range(n):
		(a, b) = map(int, input().split())
		health.append(a)
		explosion.append(b)
	bullet = max(0, health[0] - explosion[-1])
	health[0] -= max(0, health[0] - explosion[-1])
	for i in range(1, n):
		bullet += max(0, health[i] - explosion[i - 1])
		health[i] -= max(0, health[i] - explosion[i - 1])
	stdout.write(str(bullet + min(health)) + '\n')


import sys
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
	n = int(input())
	A = []
	for i in range(n):
		(a, b) = map(int, input().split())
		A.append([a, b])
		if i == 0:
			fb = A[0][0]
		else:
			fb = fb + max(A[i][0] - A[i - 1][1], 0)
	fa = fb
	for i in range(1, n):
		fb = fb - A[i - 1][0] - max(A[i][0] - A[i - 1][1], 0) + max(A[i - 1][0] - A[i - 2][1], 0) + A[i][0]
		if fb < fa:
			fa = fb
	print(fa)


import sys
readline = sys.stdin.buffer.readline
T = int(readline())
Ans = [None] * T
inf = 1 << 60
for qu in range(T):
	N = int(readline())
	AB = [tuple(map(int, readline().split())) for _ in range(N)]
	(A, B) = map(list, zip(*AB))
	CA = [0] * N
	CA[0] = max(0, A[0] - B[N - 1])
	for i in range(N):
		CA[i] = max(0, A[i] - B[i - 1])
	Sc = sum(CA)
	ans = inf
	for i in range(N):
		ans = min(ans, Sc - CA[i] + A[i])
	Ans[qu] = ans
print('\n'.join(map(str, Ans)))


import sys
from itertools import accumulate

def input():
	return sys.stdin.buffer.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 ** 18
MOD = 10 ** 9 + 7
out = []
for _ in range(INT()):
	N = INT()
	AB = []
	for i in range(N):
		(a, b) = MAP()
		AB.append((a, b))
	need = [0] * N
	for i in range(N - 1, -1, -1):
		(a, b) = AB[i]
		(na, nb) = AB[(i + 1) % N]
		if b < na:
			need[(i + 1) % N] = na - b
	sm = sum(need)
	ans = INF
	for (i, (a, b)) in enumerate(AB):
		ans = min(ans, a + sm - need[i])
	out.append(str(ans))
print('\n'.join(out))


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from heapq import heapify, heappush, heappop

def main():
	for _ in range(int(input())):
		n = int(input())
		p = []
		dif = [0] * n
		for i in range(n):
			p.append(list(map(int, input().split())))
		for i in range(n):
			dif[i] = max(0, p[i][0] - p[(i - 1) % n][1])
		su_ = sum(dif)
		ans = float('inf')
		for i in range(n):
			ans = min(ans, su_ - dif[i] + p[i][0])
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import os
import heapq
import sys, threading
import math as mt
import operator
from copy import copy
from bisect import bisect_right, bisect_left
from collections import defaultdict, deque
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 5)

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

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		ar = []
		for i in range(n):
			(a, b) = inpt()
			ar.append((a, b))
		for i in range(n):
			ar.append(ar[i])
		ans = [0] * (2 * n)
		prev = 0
		for i in range(2 * n):
			bul = max(0, ar[i][0] - prev)
			ans[i] = bul
			prev = ar[i][1]
		for i in range(1, 2 * n):
			ans[i] += ans[i - 1]
		res = ans[n - 1]
		j = 0
		for i in range(n, 2 * n):
			val = ans[i] - ans[j + 1] + ar[j + 1][0]
			j += 1
			res = min(res, val)
		print(res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from sys import stdin
from math import inf
import gc
gc.disable()
input = stdin.buffer.readline

def put():
	return [int(i) for i in input().split()]
t = int(input())
for _ in range(t):
	n = int(input())
	(a, b) = ([], [])
	for i in range(n):
		(x, y) = put()
		a.append(x)
		b.append(y)
	ans = 0
	k = inf
	for i in range(n):
		j = max(0, a[(i + 1) % n] - b[i])
		ans += j
		k = min(a[(i + 1) % n] - j, k)
	print(ans + k)


import sys
input = sys.stdin.buffer.readline
MI = 10 ** 12 + 1
t = int(input())
for _ in range(t):
	n = int(input())
	nums = [tuple(map(int, input().split())) for _ in range(n)]
	ans = 0
	mi = MI
	for (i, num) in enumerate(nums):
		(_, before_b) = nums[i - 1]
		(a, _) = num
		damage = max(0, a - before_b)
		ans += damage
		a -= damage
		mi = min(a, mi)
	print(ans + mi)


import sys
input = sys.stdin.buffer.readline
a = int(input())
for x in range(a):
	d = int(input())
	j = []
	h = 0
	mi = 0
	p = 0
	for y in range(d):
		(b, c) = map(int, input().split())
		j.append([b, c])
		if y == 0:
			h += b
		elif p - b >= 0:
			pass
		else:
			h += b - p
		p = c
	mi = h
	for y in range(d - 1):
		h -= j[y][0]
		if p - j[y][0] >= 0:
			pass
		else:
			h += j[y][0] - p
		if j[y][1] - j[y + 1][0] >= 0:
			h += j[y + 1][0]
		else:
			h -= j[y + 1][0] - j[y][1]
			h += j[y + 1][0]
		if mi > h:
			mi = h
		p = j[y][1]
	print(mi)


from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	(a, b) = map(int, stdin.readline().split())
	ttt = a
	mn = a
	if n == 1:
		print(a)
	else:
		ans = 0
		for i in range(n - 1):
			(x, y) = map(int, stdin.readline().split())
			if x > b:
				ans += x - b
				x = b
			mn = min(mn, x)
			(a, b) = (x, y)
		if ttt > b:
			ans += ttt - b
			ttt = b
		mn = min(mn, ttt)
		ans += mn
		print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for tests in range(T):
	n = int(input())
	M = [list(map(int, input().split())) for i in range(n)]
	ANS = 0
	for i in range(n):
		if M[i][0] > M[i - 1][1]:
			ANS += M[i][0] - M[i - 1][1]
			M[i][0] = M[i - 1][1]
	MIN = M[0][0]
	for i in range(n):
		MIN = min(MIN, M[i][0])
	print(ANS + MIN)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
for _ in range(int(input())):
	n = int(input())
	a = [0] * n
	b = [0] * n
	for _ in range(n):
		(a[_], b[_]) = map(int, input().split())
	ans = 0
	MIN = min(a[0], b[-1])
	for i in range(n):
		val = min(a[i], b[i - 1])
		ans += a[i] - val
		MIN = min(MIN, val)
	sys.stdout.write(str(ans + MIN) + '\n')


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	c = []
	for i in range(n):
		(a, b) = list(map(int, input().split()))
		c.append([a, b])
	sum = 0
	for i in range(n):
		x = c[i][0]
		y = max(0, c[i][0] - c[i - 1][1])
		sum += y
		if i == 0:
			diff = y - x
		else:
			diff = max(diff, y - x)
	print(sum - diff)


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
import sys, io, os
input = sys.stdin.readline
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inf = float('inf')
mod = 10 ** 9 + 7

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

def yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b
t = int(input())
answer = []
for i in range(t):
	n = int(input())
	health = [0 for i in range(n)]
	dest = [0 for i in range(n)]
	for i in range(n):
		(health[i], dest[i]) = [int(i) for i in input().split()]
	a = health[:]
	for i in range(n - 1):
		a[i + 1] = max(a[i + 1] - dest[i], 0)
	dp = [0 for i in range(n)]
	dp[0] = sum(a)
	for i in range(n - 1):
		dp[i + 1] = dp[i] - health[i] + health[i + 1] + max(health[i] - dest[i - 1], 0) - max(health[i + 1] - dest[i], 0)
	answer.append(min(dp))
print(*answer, sep='\n')


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(ans, x, y) = (0, 10 ** 13, (0, 0))
	(a0, b0) = map(int, input().split())
	for i in range(1, n):
		(a, b) = map(int, input().split())
		k = max(0, a - b0)
		ans += k
		if a - k < x:
			x = a - k
			y = (a, k)
		b0 = b
	k = max(0, a0 - b0)
	ans += k
	if a0 - k < x:
		x = a0 - k
		y = (a0, k)
	ans += y[0] - y[1]
	print(ans)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	ans = 0
	c = []
	mn = 10 ** 15
	for i in range(n):
		(a, b) = map(int, input().split())
		c.append((a, b))
	for i in range(n):
		k = max(0, c[i][0] - c[i - 1][1])
		ans += k
		mn = min(mn, c[i][0] - k)
	print(ans + mn)