poj 3685 Matrix(二分搜索之查找第k大的值)

时间:2023-03-08 17:58:32

Description

Given a N × N matrix A, whose element in the i-th row and j-th column Aij is an number that equals i2 +  × i + j2 -  × 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( ≤ N ≤ ,) and M( ≤ 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


Sample Output

-

-
- - -

Source

 题目大意:题目意思很简单。这个题目乍一看,先打n为比较小例如8的表,会觉得很有规律,大小规律是从右上往左下依次增大,但是这个规律到n为5*10^4就不一定保持了。

           解题思路:有一个规律是看得见的,j不变i增大函数值也在增大。根据这个可以对这n列二分得到<x的值,同样所求的x也是可以二分慢慢靠近最后的结果,我处理得到最后的结果是个数为m+1的最小值,所以最后mid-1即为答案。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<stdlib.h>
using namespace std;
#define inf 1<<30
#define ll long long
#define N 50006
ll n,m;
ll cal(ll i,ll j){
return i*i+*i+j*j-*j+i*j;
}
bool solve(ll mid){
ll cnt=;
for(ll j=;j<=n;j++){
ll low=;
ll high=n+;
while(low<high){
ll tmp=(low+high)>>;//另外的写法
ll ans=cal(tmp,j);
if(ans>=mid){
high=tmp;
}
else{
low=tmp+;
}
}
cnt+=low-;//另外的写法
}
if(cnt>=m) return true;
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){ scanf("%I64d%I64d",&n,&m);
ll low=-1e12;
ll high=1e12; while(low<high){
ll mid=(low+high)>>;//另外的写法
if(solve(mid)){
high=mid;
}
else{
low=mid+;
}
}
printf("%I64d\n",low-);//另外的写法 }
return ;
}

另外的写法,试比较

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<stdlib.h>
using namespace std;
#define inf 1<<30
#define ll long long
#define N 50006
ll n,m;
ll cal(ll i,ll j){
return i*i+*i+j*j-*j+i*j;
}
bool solve(ll mid){
ll cnt=;
for(ll j=;j<=n;j++){
ll low=;
ll high=n+;
ll tmp=(low+high)>>;
while(low<high){
ll ans=cal(tmp,j);
if(ans>=mid){
high=tmp;
}
else{
low=tmp+;
}
tmp=(low+high)>>;
}
cnt+=tmp-;
}
if(cnt>=m) return true;
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){ scanf("%I64d%I64d",&n,&m);
ll low=-1e12;
ll high=1e12;
ll mid=(low+high)>>;
while(low<high){
if(solve(mid)){
high=mid;
}
else{
low=mid+;
}
mid=(low+high)>>;
}
printf("%I64d\n",mid-); }
return ;
}