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.
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.
For each test case output the answer on a single line.
12 1 1 2 1 2 2 2 3 2 4 3 1 3 2 3 8 3 9 5 1 5 25 5 10Sample Output
3 -99993 3 12 100007 -199987 -99993 100019 200013 -399969 400031 -99939
这个题也是二分,考虑到每列,从上到下都是递增的,所以可以用二分来做,这就是一个找第K大的数,
我们可以利用递增的条件,先枚举答案,然后找在这个答案之前有多少个数,如果多于M,那就把答案减小,如果少于M 那就把答案增大。
注意一点,judge里的 for 循环也开了longlong,不然答案是错的,我也不知道为什么。
二分的条件判断。
如果 judge 为真, r = mid,那就写成
(l < r) r = mid, l = mid+1;
如果 judge 为真,l = mid
(l <= r)
#include <bits/stdc++.h> using namespace std; const long long INF = 1e12; long long n,m; bool judge(long long x){ long long y; long long num = 0,l,r,mid,ans; for (long long i = 1; i <= n; i++){ y = x - i*i+i*100000; l = 0; r = n; ans = 0; while(l <= r){ mid = (l + r )/2; if (mid*mid+(i+100000)*mid <= y){ l = mid +1; ans = mid; } else r = mid-1; } num += ans; } if (num >= m) return 1; else return 0; } int main() { int tt; scanf("%d",&tt); while(tt--){ scanf("%lld%lld",&n,&m); long long l = -INF,r = INF,mid,tot; while(l <= r){ mid = (l + r) / 2; if (judge(mid)) { r = mid-1; tot = mid; }else l = mid +1; } printf("%lld\n",tot); } return 0; }