您的位置:首页 > 其它

poj 3685 二分套二分 叉姐的魔法训练

2016-08-17 21:16 337 查看
Matrix

Time Limit: 6000MS Memory Limit: 65536K
Total Submissions: 6251 Accepted: 1791
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


题意:

给出一个 n*n 的矩阵,求第 m 个最小的数字

矩阵内的元素的大小是 i-th row and j-th column Aij is an number that equals i2 + 100000 × i + j2 - 100000 × j + i × j,

题解:

先对答案进行枚举二分

{

              由表达式 i2 + 100000 × i + j2 -
100000 × j + i × j 知

              当所有正项为  0 的时候,j == n  的时候是最小

              当 - 100000 * j  的时候,j == n 并且 i==n  的时候是最大

              对这个区间进行枚举二分  数字  num

}

然后我们需要计算  上叙枚举的数字  是否是第m个最小的数字

{

             第二次枚举的区间是  1     n

             同时我们发现,对表达式中  j  进行枚举的时候(j  不变), Aij  是一直保持递增的

             因此又可以对 Aij 进行枚举二分,找到小于num的数字

             因此得到一个小于num的区间,就知道这一列(j 保持不变)小于num 的数字的个数了

}

然后将所有的小于的num 的数字加起来,就知道了num是第几小的数字了

按照这个思路进行下来,就可以知道了第 m  小的数字是哪一个了

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define LL long long

LL n,m;
LL calc(LL i,LL j)
{
return (i*i+100000*i+j*j-100000*j+i*j);
}

LL deal(LL num)
{
LL cnt=0;
for(int i=1;i<=n;i++){
LL left=1,right=n;
int t=0;

while(left<=right)
{
LL mid=(left+right)>>1;
if(calc(mid,i)<=num)
t=mid,left=mid+1;
else
right=mid-1;
}
cnt+=t;
}
return cnt;
}

int main()
{
int T;
//freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--)
{
scanf("%I64d%I64d",&n,&m);
LL left=-100000*n;
LL right=3*n*n+100000*n;

LL mid,ans;
while(left<=right)
{
mid=(right+left)>>1;
if(deal(mid)>=m)
ans=mid,right=mid-1;
else
left=mid+1;
}
printf("%I64d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: