Two days ago, a woman called Fumiyo Edogawa knocked the door of Kogoro Mouri home and claimed that she is Conan's mom. Fumiyo introduced herself as Conan's mother and used fake documents to prove this. Conan, Kogoro Mouri, and his daughter Ran believed her. So, Conan went with her.
Ran was worried about Conan. After investigations, Ran discovered that Conan has been kidnapped! Ran called the police and they helped her to find Conan's location. When they arrived at that location, Ran shocked because she discovered that Conan is detained inside a locked coffin.
After examining the coffin, Ran discovered that it is locked using a modern electronic lock. Ran can open the lock only by solving T mysteries. In each mystery, Ran is giving two numbers n and a, and she needs to find the maximum number of distinct elements that can exist in a list of n positive elements with an average equals to a.
Ran knows that time is running out of her, and she must expedite in solving the mysteries to get Conan out of the coffin before his breath stopped. Ran asked you to help her in solving the mysteries. Will you leave Conan to die smothered or will you help Ran solving the mysteries?
Input
The first line contains an integer T (1 ≤ T ≤ 105), in which T is the number of mysteries.
Then T lines follow, giving the mysteries. Each line contains two integers n and a (1 ≤ n, a ≤ 109), in which n is the number of elements in the list, and a is the required average of that list.
Output
For each test case, print a single line containing the maximum number of distinct elements that can exist in a list of n positive elements with an average equals to a.
Example
Input
3 2 4 5 1 8 4
Output
2 1 7
Note
The average of a list of n elements x1, x2, ..., xn is defined as the ratio between the sum of the n elements and n. More formally:
In the first test case, Ran is asked to find the maximum number of distinct elements that can exist in a list of 2 positive elements with an average equals to 4. Ran can choose a list such as [3, 5]. So, the number of distinct elements is 2.
求 n个数的平均值等于a的集合中不同元素的个数
要求最大不同元素 所以从小到大选
则前m 个元素和为(m + 1)* m / 2 剩余元素和最小为 n - m
则 如果 (m + 1) * m + (n - m) <= n * a 就更新Max 为max(m, Max)
二分寻找最大的m的值即为所求
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll n, a;
ll flag = -1;
void f(ll l, ll r)
{
if(l > r)return;
ll m = (l +r) / 2;
if(m*(m + 1) + 2*(n - m) <= n * a * 2)
{
flag = max(m, flag);
if(m*(m + 1) == n * a * 2)return;
}
if(m * (m + 1)+ 2*(n - m) < n * a * 2)f(m + 1, r);
if(m * (m + 1) + 2*(n - m) > n * a * 2)f(l, m - 1);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%lld %lld", &n, &a);
flag = 1;
f(1, n);
printf("%lld\n", flag);
}
return 0;
}