#P9815. wbyblD

wbyblD

Background

Problem D. I do not want to be hacked!!!

Problem Description

There are n+2n+2 points in a line, numbered 0∼n+10\sim n+1. For point ii, there are two integers ai,bia_i, b_i, where 0≤i≤n+10\le i\le n+1. Initially, define a0=b0=an+1=bn+1=0a_0=b_0=a_{n+1}=b_{n+1}=0.

Suppose you are currently at point xx, and the current moving direction is yy. Initially, x=0,y=1x=0, y=1.

You will move in the following way until after some change of x,yx, y you get x=0,y=−1x=0, y=-1 or x=n+1,y=1x=n+1, y=1.

  • If y=1y=1, first increase xx by 11. Then if ax>0a_x>0, set yy to −1-1; otherwise, keep yy unchanged. Finally, decrease axa_x by 11.
  • If y=−1y=-1, first decrease xx by 11. Then if bx>0b_x>0, set yy to 11; otherwise, keep yy unchanged. Finally, decrease bxb_x by 11.

Ask which point number xx will be at when the process ends. In fact, in the end, xx can only be at point 00 or point n+1n+1.

Input Format

This problem has multiple sets of testdata. The first line contains a positive integer TT, the number of test cases, followed by TT test cases.

For each test case, the first line contains a positive integer nn.

Then follow nn lines, each containing two non-negative integers ai,bia_i, b_i, representing the initial values of ai,bia_i, b_i.

Output Format

For each test case, output one line with one integer, indicating which point number xx will be at when the process ends.

3
1
1 1
3
0 1
1 1
1 0
3
0 1
2 3
4 5
0
4
0

Hint

Sample Explanation

For the 11st sample test case, (x,y)(x,y) changes as (0,1)→(1,1)→(1,−1)→(0,−1)(0,1)\to (1,1)\to (1,-1)\to (0,-1).

For the 22nd sample test case, (x,y)(x,y) changes as $(0,1)\to (1,1)\to (2,1)\to (2,-1)\to (1,-1)\to (1,1)\to (2,1)\to (3,1)\to (3,-1)\to (2,-1)\to (2,1)\to (3,1)\to (4,1)$.

For the 33rd sample test case, (x,y)(x,y) changes as $(0,1)\to (1,1)\to (2,1)\to (2,-1)\to (1,-1)\to (1,1)\to (2,1)\to (2,-1)\to (1,-1)\to (0,-1)$.

Constraints and Notes

For the first 30%30\% of the test points, it is guaranteed that n,ai,bi≤10n,a_i,b_i\le 10.

For the first 60%60\% of the test points, it is guaranteed that ∑n≤5000\sum n\le 5000.

For the other 20%20\% of the test points, it is guaranteed that T=10T=10, n=105n=10^5, and ai,bia_i,b_i are generated uniformly at random within the specified range. In particular, it is guaranteed that for all test points except this part, T≠10T\ne 10.

For all test points, it is guaranteed that 1≤T≤1041\le T\le 10^4, 1≤n≤1051\le n\le 10^5, 1≤∑n≤1061\le \sum n\le 10^6, 0≤ai,bi≤1060\le a_i,b_i\le 10^6.

Translated by ChatGPT 5