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;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Reast1nPeace/article/details/79969347
文章标签: acm 二分搜索
个人分类: 二分
上一篇poj1064 二分答案
下一篇poj 1759 二分
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭