题意:
给一个n * n 的矩阵, 其中每个元素的大小为:
i * i + 100000 * i + j * j - 100000 * j + i * j
现在给n和m,求这个矩阵中第 m 大的元素是什么。
解析:
发现上面那个式子是按照,每一列,从小到大递增的。
所以可以先二分设定一个mi元素,然后按照每一列来二分统计比它小的元素有多少个。
如果比它小的元素个数大于m,则说明原来设定的元素mi太大;
反之,原来设定的元素太小。
开始的时候wa了,从讨论区找了几组数据,然后发现n和m没开LL。。。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = acos(-1.0);
const double ee = exp(1.0);
const int maxn = 50000 + 10;
LL n, m;
LL cal(LL i, LL j)
{
return i * i + 100000 * i + j * j - 100000 * j + i * j;
}
bool ok(LL d)
{
LL cnt = 0;
for (int j = 1; j <= n; j++)
{
int lo = 0, hi = n + 1;
for (int k = 0; k < 20; k++)
{
int i = (lo + hi) >> 1;
if (cal(i, j) < d)
lo = i;
else
hi = i;
}
cnt += lo;
}
return cnt < m;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
scanf("%lld%lld", &n, &m);
LL lo = -100000 * n, hi = n * n + 100000 * n + n * n + n * n;
for (int i = 0; i < 50; i++)
{
LL mi = (lo + hi) >> 1;
if (ok(mi))
lo = mi;
else
hi = mi;
}
printf("%lld\n", lo);
}
return 0;
}
/*
10
50000 2500000000
48888 2000000000
47777 1500000000
46666 1200000000
45555 1000000000
44444 900000000
43333 800000000
42222 700000000
41111 600000000
40000 500000000
7500000000
5129139981
3273537711
2261727633
1634929103
1368488613
1096871427
820144979
538443492
251994213
*/