51NOD 1105 第K大的数 【二分】

1105K大的数
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
收藏
关注
数组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 129个数。
Input1行:2个数NK,中间用空格分隔。N为数组的长度,K对应第K大的数。(2 <= N <= 500001 <= K <= 10^9)
第2 - N + 1行:每行2个数,分别是A[i]和B[i]。(1 <= A[i],B[i] <= 10^9)

Output

输出第K大的数。

Input示例

3 2
1 2
2 3
3 4

Output示例

9

李陶冶 (题目提供者)

原来二分还能这样用!
对给定的x
枚举数组a
二分法确定b中多少个数>=x/a
那就在n*log(n)内找到c中>=x的数的个数

那只要再用二分法求出 c中>=x的数的个数 = k 的这个x就行了
复杂度n*log(n)*log(max(a[i])*max(b[i]))


#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<time.h>
#include<math.h>
#include<list>
#include<cstring>
#include<fstream>
#include<queue>
#include<sstream>
//#include<memory.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define INF 1000000007
#define pll pair<ll,ll>
#define pid pair<int,double>

const int N = 5e4+5;

ll a[N];
ll b[N];

pll f(ll x,ll n){//first:>=x的数的个数 second:>=x的数的最小值
    ll ans1=0,ans2=1e18+5;
    for(int i=0;i<n;++i){
        ll tmp = x/a[i] + (x%a[i]!=0);
        ll*index = lower_bound(b,b+n,tmp);
        if(index!=b+n){
            ans1 += n - (index - b);
            ans2 =min(ans2,(ll)*index*a[i]);
        }
    }
    return make_pair(ans1,ans2);
}

ll binarySearch(ll n,ll k){
    sort(a,a+n);
    sort(b,b+n);
    ll l = a[0]*b[0],r = a[n-1]*b[n-1];
    while(l<r){
        ll mid = (l+r)/2;
        pll t = f(mid,n);//mid为第几大
        if(t.first>k){
            l=mid+1;
        }
        else{
            r=mid;
            if(t.first==k){
                return t.second;
            }
        }
    }
}

int main()
{
    //freopen("/home/lu/Documents/r.txt","r",stdin);
    //freopen("/home/lu/Documents/w.txt","w",stdout);
    ll n,k;
    while(~scanf("%lld%lld",&n,&k)){
        for(int i=0;i<n;++i){
            scanf("%lld%lld",a+i,b+i);
        }
        printf("%lld\n",binarySearch(n,k));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值