| 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;
}

本文介绍了一种高效算法,用于解决寻找特定矩阵中第m小的元素的问题。该矩阵的元素通过一个特定公式计算得出。文章详细阐述了如何通过二分枚举的方法来缩小搜索范围,最终精确找到目标元素。
297

被折叠的 条评论
为什么被折叠?



