对二分的一些新的理解
对于二分的一开始理解还是基于lower_bound,upper_bound的功能实现过程。
对于几种不同的二分之前也初步了解了一些,其中主要为一次二分操作就能解决的问题,Matrix这个题提供了一种新的二分思想
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
第一步:
计算复杂度可以看出利用暴力方法(
N2∗log2N
)无法解出,所以要利用二分来优化。
寻找单调性,根据线性关系可以推导出
i2+1e5×i+j2−1e5×j+i×j
=
(i+5e4)2+(j+5e4)2−5e9+i∗j
对于i是单调递增的,我们可以根据i来进行二分来进行优化。
第二步:
首先确定一个思路,二分的答案区间中mid值作为check()函数的衡量标准,因为我们要寻找第M小的数字,所以我们的目标就是要找出一个左边界值使得有M-1个数字比它小。
然后再确定二分区间,直接取-INF,INF;
#define ll long long
ll l=-INF,r=INF;
while(l<=r){
ll mid = (l+r)/2;
if (Binary(mid) < M) l = mid+1;
else r = mid-1;
}
printf("%I64d\n",l);
第三步:
对于Binary()函数,根据我们上面的推导,我们可以遍历一遍j,然后二分一遍i(由于其有单调性),找到每个
f(i,j)
(假定我们把题目所给出的取值函数
f(i,j)=i2+1e5×i+j2−1e5×j+i×j
)
使得
f(i,j)
小于给出的mid值,并统计其数量,再传回主函数
ll check(ll i,ll j)
{
return i*i + 100000*1LL*i + j*j - 100000*1LL*j + i*j;
}
ll Binary(ll x)
{
ll res = 0;
for(ll i=1;i<=N;i++)
{
ll L=1,R=N;
while(L<=R)
{
ll mid = (R+L)/2;
if(check(mid,i) <= x) L=mid+1;
else R=mid-1;
}
res+=L-1;
}
return res;
}
注意点:
1.注意二分的过程和范围,统计的时候的每次增加的个数是对应lower_bound结果减1
2.确定二分关系的最主要前提是单调性,根据这个条件,可以根据单调性转化为二分优化。