Circle of Monsters

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.

Example

input

1
3
7 15
2 14
5 3

output

6

Solution:

#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}());
const ll mod=1000000007;
int rnd(int x) { return mrand() % x;}
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
// head

const int N=301000;

int _,n;
ll extra[N],a[N],b[N];
int main() {
for (scanf("%d",&_);_;_--) {
scanf("%d",&n);
rep(i,0,n) scanf("%lld%lld",a+i,b+i);
ll s=0,d=1ll<<60;;
		rep(i,0,n) {
			extra[i]=max(0ll,a[i]-b[(i+n-1)%n]);
			s+=extra[i];
		//	printf("%d %lld\n",i,extra[i]);
		}
		rep(i,0,n) d=min(d,s-extra[i]+a[i]);
		printf("%lld\n",d);
	}
}