51Nod 1105 第K大的数 ( 二分

1105 第K大的数

题目描述

数组A和数组B,里面都有n个整数。数组C共有n^2个整数,分别是A[0] * B[0],A[0] * B[1] ……A[1] * B[0],A[1] * B[1]……A[n - 1] * B[n - 1](数组A同数组B的组合)。求数组C中第K大的数。
例如:A:1 2 3,B:2 3 4。A与B组合成的C包括2 3 4 4 6 8 6 9 12共9个数。

输入

第1行:2个数N和K,中间用空格分隔。N为数组的长度,K对应第K大的数。(2 <= N <= 50000,1 <= K <= 10^9)
第2 - N + 1行:每行2个数,分别是A[i]和B[i]。(1 <= A[i],B[i] <= 10^9)

输出

输出第K大的数。

样例

Input示例
3 2
1 2
2 3
3 4
Output示例
9

题意

排序后二分即可

AC代码

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;

#define ls              st<<1
#define rs              st<<1|1
#define fst             first
#define snd             second
#define MP              make_pair
#define PB              push_back
#define LL              long long
#define PII             pair<int,int>
#define VI              vector<int>
#define CLR(a,b)        memset(a, (b), sizeof(a))
#define ALL(x)          x.begin(),x.end()
#define ber(i,s,e) for(int i=(s); i<=(e); i++)
#define rep(i,s,e) for(int i=(s); i>=(e); i--)

const int INF = 0x3f3f3f3f;
const int MAXN = 1e5+10;
const int mod = 1e9+7;
const double eps = 1e-8;

void fe() {
  #ifndef ONLINE_JUDGE
      freopen("in.txt", "r", stdin);
      freopen("out.txt","w",stdout);
  #endif
}
LL read()
{
   LL x=0,f=1;char ch=getchar();
   while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
   while (ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
   return x*f;
}

LL arr[MAXN], brr[MAXN];
LL n, k;

LL check(LL x) {
    LL j = n, sum = 0;
    for(int i = 1; i <= n; i++) {
        while(j) {
            if(arr[i]*brr[j] > x)
                j--;
            else
                break;
        }
        sum += j;
    }
    return sum;
}
int main() {
    ios::sync_with_stdio(false);
    cin >> n >> k;
    for(int i = 1; i <= n; i++) {
        cin >> arr[i] >> brr[i];
    }
    sort(arr+1,arr+n+1);
    sort(brr+1,brr+1+n);
    LL l = arr[1]*brr[1], r = arr[n]*brr[n];
    LL p = n*n-k+1;
    LL mid, ans=0;
    while(l <= r) {
        mid = l + (r-l)/2;
        if(check(mid) >= p) 
            r = mid-1;
        else
            l = mid+1;
    }
    if(check(r+1) >= p) 
        r++;
    cout << r << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/wang2332/article/details/80313293
今日推荐