C. Circle of Monsters
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 ai 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 bi 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≤T≤150000) — the number of test cases.
Then the test cases follow, each test case begins with a line containing one integer n (2≤n≤300000) — the number of monsters. Then n lines follow, each containing two integers ai and bi (1≤ai,bi≤1012) — 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
inputCopy
1
3
7 15
2 14
5 3
outputCopy
6
//题目意思大概就是n种怪物构成环 一种怪物有ai的血量,bi的爆炸量
// 你可以攻击怪物一次造成1点伤害(怪物血量减一)当怪物的血量<=0的时候可以自身爆炸
//其伤害对下一个怪物造成影响,即((i+1)%n)问你最小需要对怪物造成多少伤害才能全部杀死怪物
//题解 贪心 计算改怪物的伤害能不能炸死下一个 如果不能 就把下一个怪物的血量减少到能。然后取最优的怪物开始伤害
#include<iostream>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<string>
#define ll long long
int vis[123];
using namespace std;
ll gcd(ll a,ll b){
return b==0?a:gcd(b,a%b);
}
ll a[1000000];
ll b[1000000];
ll c[1000000];
ll mi=1e18;
ll isN(int N){
ll ans=0;
ll mi=1e19;
for(int i=1;i<=N-1;i++)
{
if(b[i]<a[i+1]) //不能炸死 血量减为能炸死的血量
{
ans+=(a[i+1]-b[i]);
a[i+1]=b[i];
}
if(a[i]<mi){ //取最优的怪物开始炸
mi=a[i];
}
}
if(a[N]<mi) //循环外记得判断点a【N】的血量
mi=a[N];
if(b[N]<a[1]){ //特判怪物【N】炸【1】
ans+=(a[1]-b[N]);
a[1]=b[N];
}
if(a[1]<mi)
mi=a[1];
return ans+mi;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%lld %lld",&a[i],&b[i]);
}
cout<<isN(n)<<endl;
}
return 0;
}