POJ 3685 Matrix (二分搜索)

Matrix
Time Limit: 6000MS   Memory Limit: 65536K
Total Submissions: 5131   Accepted: 1381

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 因为只有i>0的时候 关于i的函数是单调的

- - 查了半天bug

AC代码如下:

//
//  Created by TaoSama on 2015-04-28
//  Copyright (c) 2015 TaoSama. All rights reserved.
//
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>

using namespace std;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int N = 1e5 + 10;

long long n, m;

bool check(long long x) {
    long long cnt = 0;
    for(int j = 1; j <= n; ++j) {
        int l = 0, r = n + 1;
        while(l + 1 < r) {
            int i = l + r >> 1;
            long long col = 1LL * j * j + 1LL * i * i + 1LL * i * j + (i - j) * 100000LL;
            if(col < x) l = i;
            else r = i;
        }
        cnt += l;
    }
    return cnt < m;
}

int main() {
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
//  freopen("out.txt","w",stdout);
#endif
    ios_base::sync_with_stdio(0);

    int t; cin >> t;
    while(t--) {
        cin >> n >> m;
        long long l = -100000 * n, r = 3 * n * n + 100000 * n;
        while(l + 1 < r) {
            long long mid = l + r >> 1;
            if(check(mid)) l = mid;
            else r = mid;
        }
        cout << l << '\n';
    }
    return 0;
}


你可能感兴趣的:(POJ 3685 Matrix (二分搜索))