POJ - 3685 Matrix
POJ - 3685 Matrix
二分套二分
Matrix - POJ 3685 - Virtual Judge (vjudge.net)
\(f(i,j)=i^2+10^5*i+j^2-10^5*j+i*j\)
\(f\) 关于 \(i\) 单调递增,关于 \(j\) 单调递减
要找第 \(m\) 小的 $ f(i,j)$, 则可二分答案,check 函数返回矩阵中有多少元素小于当前的二分值
check 中求有多少元素小于某个值的过程中,可以枚举 \(j\), \(i\) 单调递增,所以可以二分出每个 \(j\) 对应有多少个 \(i\) 的 \(f(i,j)\) 小于当前的二分值,
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
const ll N = 1e5;
int n;
ll m;
ll f(ll x, ll y)
{
return x * x + N * x + y * y - N * y + x * y;
}
ll check(ll x)
{
ll cnt = 0;
for (int j = 1; j <= n; j++)
{
int l = 0, r = n + 1;
while(l + 1 != r)
{
int mid = l + r >> 1;
if (f(mid, j) < x)
l = mid;
else
r = mid;
}
cnt += l;
}
return cnt;
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T;
cin >> T;
while(T--)
{
cin >> n >> m;
ll l = -1e12, r = 1e12;
while(l + 1 != r)
{
ll mid = l + r >> 1;
if (check(mid) < m)
l = mid;
else
r = mid;
}
cout << l << endl;
}
return 0;
}