C. Circle of Monsters

 

You are playing another computer game, and now you have to slay nn monsters. These monsters are standing in a circle, numbered clockwise from 11 to nn. Initially, the ii-th monster has aiai health.

You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by 11 (deals 11 damage to it). Furthermore, when the health of some monster ii becomes 00 or less than 00, it dies and explodes, dealing bibi damage to the next monster (monster i+1i+1, if i<ni<n, or monster 11, if i=ni=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 nn monsters in the circle.

Input

The first line contains one integer TT (1≤T≤1500001≤T≤150000) — the number of test cases.

Then the test cases follow, each test case begins with a line containing one integer nn (2≤n≤3000002≤n≤300000) — the number of monsters. Then nn lines follow, each containing two integers aiai and bibi (1≤ai,bi≤10121≤ai,bi≤1012) — the parameters of the ii-th monster in the circle.

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

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
#include <bits/stdc++.h>
#define rush() int T;cin>>T;while(T--)
#define sf(a) scanf("%d\n",&a)
#define go(a) while(scanf("%d",&a)!=EOF)
#define ms(a,b) memset(a,b,sizeof a)
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define pf(a) printf("%.2lf",a)
#define E 1e-8
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int idata=3*1e5+5;
const double pi=acos(-1.0);

int i,j,k;
ll n,m,ans,t;
ll blood[idata],injure[idata],res[idata];
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    rush()
    {
        cin>>n;
        for(i=1;i<=n;i++)
            cin>>blood[i]>>injure[i];
        ll sum=0;
        for(i=1;i<=n;i++)
        {
            if(i==1) res[i]=blood[i]-injure[n];
            else res[i]=blood[i]-injure[i-1];

            if(res[i]>0) sum+=res[i];
        }
        ans=1e18;//一定要这么大
        for(i=1;i<=n;i++)//枚举首杀monster
        {
            if(res[i]>0) ans=min(ans,sum-res[i]+blood[i]);//前面的炸不死monster
            else ans=min(ans,sum+blood[i]);
        }
        cout<<ans<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值