您的位置:首页 > 其它

poj 3685 Matrix 二分里套二分

2015-08-26 21:24 351 查看
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 + 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

给一个矩阵,第i行第j列的数的大小为 i^2 + 100000 × i + j^2 - 100000 × j + i × j

给出矩阵的大小,求第m小的数。。。。

咋一看,打个表,发现中右上角到左下角递减。。以为是规律。。那么你错了。。。。

对于行求导 f(i)’=2*i+100000+j>0恒成立; //恒增,,因此行的数是单调的,,但是

对列求导 f(j)’=2*j-100000+i; 单调性就不能确定了,,当数很大的是,,上边所谓的规律就不对了。。。

因此,,这个题,,还是得用二分。。。

首先我们二分的是答案,,即即m小的数是什么。。。那么对于一个给定的数,,我可以用二分求出每行比这个数小的数的个数。。因为行是单调的。。再判断数量是多了还是少了。。。再返回到二分答案那个二分那,继续二分找到解为止。。。

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<stack>
#pragma comment(linker,"/STACK:102400000,102400000")
#define pi acos(-1.0)
#define EPS 1e-6
#define INF (1<<24)
using namespace std;
long long int n,m;
long long int cal(long long int i,long long int j)
{
long long int p=i*i+100000*i+j*j-100000*j+i*j;
return p;
}
// f(i)'=2*i+100000+j;  //恒增
// f(j)'=2*j-100000+i;  //不定
long long int sum(long long int x) //统计比x小的个数
{
long long int num=0;
for(int j=1;j<=n;j++) //枚举每一列
{
int l=1,r=n;  //按行二分
while(l<=r)
{
int mind=(l+r)>>1;
long long int v=cal(mind,j);
if(v<=x) l=mind+1; //递增
else r=mind-1;
}
num=num+l-1;
}
return num;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%I64d %I64d",&n,&m);
long long int left=-1e10;
long long int right=1e10;
long long int cnt,mind;
while(left<=right)  //二分答案。。。
{
mind=(left+right)>>1;
cnt=sum(mind);
if(cnt<m) left=mind+1;
else right=mind-1;
}
printf("%I64d\n",left);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: