基准时间限制: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 12共9个数。
Input
第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)
Output
输出第K大的数。
Input示例
3 2 1 2 2 3 3 4
Output示例
9
二分答案m, 统计大于等于m的数出现的次数有多少个
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
#define maxn 50005
using namespace std;
typedef long long ll;
ll num1[maxn], num2[maxn];
int n, k;
bool judge(ll m){
ll ans = 0;
for(int i = 0; i < n; i++){
if(num1[i] >= m){
ans += n;
}
else{
ll d = m / num1[i];
if(m % num1[i] != 0)
d++;
int h = lower_bound(num2, num2+n, d) - num2;
ans += n - h;
}
if(ans >= k)
return false;
}
return true;
}
int main(){
// freopen("in.txt", "r", stdin);
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i++){
scanf("%I64d%I64d", num1+i, num2+i);
}
sort(num1, num1+n);
sort(num2, num2+n);
ll l = 1, r = num1[n-1] * num2[n-1] + 1;
while(l < r){
ll mid = (l + r) >> 1;
if(judge(mid))
r = mid;
else
l = mid + 1;
}
ll maxs = l;
for(int i = 0; i < n && l > num1[i]; i++){
ll d = l / num1[i];
int h = lower_bound(num2, num2+n, d) - num2;
if(h == n)
h--;
if(num2[h] * num1[i] >= l && h > 0)
h--;
if(num2[h] * num1[i] < l){
if(maxs == l)
maxs = num2[h] * num1[i];
else
maxs = max(maxs, num2[h] * num1[i]);
}
}
printf("%I64d\n", maxs);
return 0;
}