B. A and B-------思维(难)

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).

题意:给你a和b,第一次操作a或b+1,第二次操作a或b +2.。。。。直至a==b
请问最小需要多少次操作。

解析:
假设有三次操作.分别+1,+2,+3.如果给a +1,+2,+3那么差值为6 反之为-6
如果给a -1 +3 +2 那么差值为4,反之为-4
如果给a +1 +3 -2 那么差值为2,反之为-2
如果a +1,+2,-3 那么差值为0,反之为0

根据等差数列求和公式 x次操作后和为 x*(x+1)/2 。虽然a的范围再1e9,但是根据公式可知 范围缩小到1e5,直接暴力枚举,只要满足两个条件即可。
第一 x*(x+1)/2>=(a-b);
第二 x*(x+1)/2和(a-b)同奇偶性(很重要)

扫描二维码关注公众号,回复: 8857911 查看本文章

#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;
	}
}

发布了309 篇原创文章 · 获赞 6 · 访问量 5255

猜你喜欢

转载自blog.csdn.net/qq_43690454/article/details/104080388