Given a N × N matrix A, whose element in the i-th row and j-th column Aij is an number that equals i2 + 100000 × i + j2 - 100000 × j + i × j, you are to find the M-th smallest element in the matrix.
Input
The first line of input is the number of test case.
For each test case there is only one line contains two integers, N(1 ≤ N ≤ 50,000) and M(1 ≤ M ≤ N × N). There is a blank line before each test case.
Output
For each test case output the answer on a single line.
Sample Input
12
1 1
2 1
2 2
2 3
2 4
3 1
3 2
3 8
3 9
5 1
5 25
5 10
Sample Output
3
-99993
3
12
100007
-199987
-99993
100019
200013
-399969
400031
-99939
第一眼看到这个题目,打了个表,wa了一万年,打表那个规律是i越大,j越小 ,值越大,其实看那个表达式,i越大值越大,但是
当i不同时,j越大值不一定越大 所以那个规律是错的
正解是
当j相同时 i越大值越大, 当i相同时,j越大值越小
所以
二分答案,在二分答案时再枚举j,二分求出每列<=二分答案的值的数量,将所有列的<=二分答案的值的数量加起来,假设用num计数,num就是二分答案时第num大数,
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstdlib>
#include<deque>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>P;
const int len=1e5+5;
const ll mod=998244353;
const ull seed=131;
ll solve(ll i,ll j)
{
return i*i+100000*i+j*j-100000*j+i*j;
}
ll n,k;
int judge(ll m)
{
ll num=0;
for(ll i=1;i<=n;++i)
{
ll l=0,r=n,mid;//边界问题也要注意
while(l<r)
{
mid=(l+r+1)/2;
if(solve(mid,i)<=m)l=mid;
else r=mid-1;
}
num+=l;
}
return num>=k;
}
int main()
{
int t;
cin>>t;
while(t--)
{
scanf("%lld%lld",&n,&k);
ll l=-1e12,r=1e12,mid;
while(l<r)
{
mid=(l+r)>>1;
//注意这里,/是向0取整-5/2=-2
// >> 是向左取整 (-5)>>1=-3
if(judge(mid))r=mid;
else l=mid+1;
}
printf("%lld\n",r);
}
}