Given a × matrix , whose element in the i-th row and j-th column is an number that equals + × + - × + × , you are to find the M-th smallest element in the matrix.
题意:有一个N × N的矩阵,其中 = + × - × + + × ,问这个矩阵中,第M小的数是多少?
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define ll long long
using namespace std;
ll n, m;
ll cal(int i, int j) { return ll(i + 100000 + j) * i + ll(j - 100000) * j; }
bool check(ll x)
{
ll sum = 0;
for (int i = 1; i <= n; ++i)
{
int l = 1, r = n;
while (l <= r)
{
int mid = l + r >> 1;
if (cal(mid, i) <= x)
l = mid + 1;
else
r = mid - 1;
}
sum += l - 1;
}
return sum < m;
}
int main()
{
IOS;
int t;
cin >> t;
while (t--)
{
cin >> n >> m;
ll l = -((ll)n * n * 3 + 100000 * n), r = (ll)n * n * 3 + 100000 * n;
while (l <= r)
{
ll mid = l + r >> 1;
if (check(mid))
l = mid + 1;
else
r = mid - 1;
}
printf("%lld\n", l);
}
return 0;
}