第k大数 两个数组元素相乘后的第k大

分析:二分,两边夹,细节见代码。(复杂度为O(2nlog(maxa*maxb)))

代码一:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long LL;

const int MAXN = 100010;

LL a[MAXN], b[MAXN];
int n,k;

bool check(LL val)//统计比val小的数的个数cnt,看cnt比k大还是比k小
{
    int cnt = 0;
    for(int i = 0, j = n - 1; i < n; ++i)
    {
        while(j >= 0 && a[i] * b[j] > val) --j;
        cnt += j + 1;//j+1指每一列数中比val大的数
    }
    return cnt >= k;
}

LL solve()//二分查找第k大的数
{
    LL l = a[0] * b[0], r = a[n - 1] * b[n - 1];
    while(l < r)
    {
        LL mid = (l + r) >> 1;
        if(!check(mid)) l = mid + 1;
        else r = mid;
    }
    return l;
}

int main(){
    scanf("%d%d",&n,&k);
    for(int i = 0; i < n; ++i) scanf("%lld%lld", &a[i],&b[i]);
    sort(a, a + n);
    sort(b, b + n);
    k=n * n - k + 1;
    printf("%lld\n", solve());
    return 0;
}

 

代码二:

#pragma comment(linker, "/STACK:102400000,102400000")///手动扩栈
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cstdio>
#include<bitset>
#include<vector>
#include<cmath>
#include<ctime>
#include<stack>
#include<queue>
#include<deque>
#include<list>
#include<set>
#include<map>
using namespace std;
const int maxn=1e5+1;
const double inf=999999999;
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define For(i,t,n) for(int i=(t);i<(n);i++)
typedef long long  LL;
typedef double DB;
typedef pair<int,int> P;
#define bug printf("---\n");
#define mod  1000000007

int a[maxn],b[maxn];
int n,k;

bool pan(LL num){
    int cnt=0;
    for(int i=0; i<n; i++)
        cnt+=n-(upper_bound(b,b+n,num/a[i])-b);//查找是否比num大的元素的个数
    cout<<num<<" "<<cnt<<endl;
    return cnt>k-1;
}

void slove(){
    LL l=(LL)a[0]*b[0];
    LL h=(LL)a[n-1]*b[n-1];//在最大最小值之间二分答案
    while(l<=h){
        LL mid=(LL)(l+h)/2;
        if(pan(mid))
            l=mid+1;
        else
            h=mid-1;
    }
    cout<<l<<endl;
}

int main(){
    cin>>n>>k;
    for(int i=0;i<n;i++) cin>>a[i]>>b[i];
    sort(a,a+n);
    sort(b,b+n);
    slove();
    return 0;
}

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值