CF BUDDY
← Problems·

1334C · Circle of Monsters

1600 · brute force, constructive algorithms, greedy

Problem: 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 aia_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 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 bib_i 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 Format: The first line contains one integer TT (1T1500001 \le T \le 150000) — the number of test cases.

Then the test cases follow, each test case begins with a line containing one integer nn (2n3000002 \le n \le 300000) — the number of monsters. Then nn lines follow, each containing two integers aia_i and bib_i (1ai,bi10121 \le a_i, b_i \le 10^{12}) — 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 Format: For each test case, print one integer — the minimum number of bullets you have to fire to kill all of the monsters.

Sample Cases

Case 1

Input

1
3
7 15
2 14
5 3

Output

6

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback