poj3685 二分答案+找规律

题目:

Matrix
Time Limit: 6000MS Memory Limit: 65536K
Total Submissions: 7915 Accepted: 2388

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.

题意:(来自vj)有一个N阶方阵 第i行,j列的值Aij =i2 + 100000 × i + j2 - 100000 × j + i × j,需要找出这个方阵的第M小值.


思路: 由A[i][j] = i2 + 100000 × i + j2 - 100000 × j + i × j 得:

A[i+1][j] = A[i][j] + (2*i + j + 1 + 100000);(同一列递推式)

A[i][j+1] = A[i][j] + (2*j + i + 1 - 100000); (同一行递推式)

由此可知,在列方向上,矩阵单调递增,而在行方向上上,当(2*j + i + 1)> 100000 时,递增,反之递减。

于是我们可以首先二分答案(即第m大的数),然后再在每一列中二分搜索有多少数要小于等于该值,将每一列的值求和即可得出与第一次二分答案得到的数的规律。

代码:

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<set>
#define sd(x) scanf("%d",&x)
#define ss(x) scanf("%s",x)
#define sc(x) scanf("%c",&x)
#define sf(x) scanf("%f",&x)
#define slf(x) scanf("%lf",&x)
#define slld(x) scanf("%lld",&x)
#define me(x,b) memset(x,b,sizeof(x))
#define pd(d) printf("%d\n",d);
#define plld(d) printf("%lld\n",d);
#define eps 1.0E-8
// #define Reast1nPeace

typedef long long ll;

using namespace std;

const ll INF = 0x3f3f3f3f3f3f3f;

ll x,y;

ll get(ll i,ll j){
	return i*i + 100000*i + j*j -100000*j + i*j; 
}

bool judge(ll num){
	ll sum = 0;
	for(int j = 1 ; j<=x ; j++){
		ll l = 1 ; ll r = x;
		ll ans = 0;
		while(l<=r){
			ll mid = (l+r)/2;
			if(get(mid,j) <= num){
				ans = mid;
				l = mid+1;
			}
			else{
				r = mid-1;
			}
		}
		sum += ans;
	}
	return sum >= y;
}

int main(){
#ifdef Reast1nPeace
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
#endif
	ios::sync_with_stdio(false);
	int T;
	cin>>T;
	while(T--){
		cin>>x>>y;
		
		ll l = -INF; ll r = INF;
		ll ans;
		while(l<=r){
			ll mid = (l+r)/2;
			if(judge(mid)){
				ans = mid;
				r = mid-1;
			}
			else{
				l = mid+1;
			}
		}
		cout<<ans<<endl;
	} 
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值