B. A and B ------- thinking (hard)

You are given two integers a and b. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by 1; during the second operation you choose one of these numbers and increase it by 2, and so on. You choose the number of these operations yourself.

For example, if a=1 and b=3, you can perform the following sequence of three operations:

add 1 to a, then a=2 and b=3;
add 2 to b, then a=2 and b=5;
add 3 to a, then a=5 and b=5.
Calculate the minimum number of operations required to make a and b equal.

Input
The first line contains one integer t (1≤t≤100) — the number of test cases.

The only line of each test case contains two integers a and b (1≤a,b≤109).

Output
For each test case print one integer — the minimum numbers of operations required to make a and b equal.

Example
inputCopy
3
1 3
11 11
30 20
outputCopy
3
0
4
Note
First test case considered in the statement.

In the second test case integers a and b are already equal, so you don’t need to perform any operations.

In the third test case you have to apply the first, the second, the third and the fourth operation to b (b turns into 20+1+2+3+4=30).

Meaning of the questions: to give you a and b, a first operation or b + 1, a second operation or b +2 .. . . . Until a == b
ask how many operations the minimum required.

Analysis:
Suppose there are three operations + 1, + 2, + 3 A + 1 if a + 2, 3 + 6 and vice versa then the difference is -6.
If you give a -1 +3 +2 difference is then 4, whereas -4
If then a +1 +3 -2 to 2 difference, and vice versa -2
if a + 1, + 2, -3 then the difference is 0, and 0 otherwise

column summation according to the number of arithmetic equation after operations and x is x * (x + 1) / 2. Although the scope of a re-1E9, but according to the formula indicates narrow 1E5, direct violence enumeration, to as long as two conditions are met.
A first x * (x + 1) / 2> = (ab);
a second x * (x + 1) / 2 and (ab) the same parity (very important)


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int t,a,b;
int main()
{
	cin>>t;
	while(t--)
	{
		cin>>a>>b;
		if(a<b) swap(a,b);
		if(a==b)
		{
			puts("0");
			continue;
		}
		int ans=1;
		while(1)
		{
			ll sum=ans*(ans+1)/2;
			if(sum>=(a-b)&&sum%2==(a-b)%2) break;
			ans++;
		}
		cout<<ans<<endl;
	}
}

Published 309 original articles · won praise 6 · views 5255

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/104080388