Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1540
Topic
For t groups of data, the lengths of the two arrays a and b in each group are n and m respectively. Now we need to multiply them by two to get n*m numbers. What is the k-th largest number among these numbers?
Ideas
The range of n,m is very large and 1e5. If you find O(n*m) directly, it will time out. You can consider the answer of dichotomy.
Sort the a, b arrays from small to large, then the left boundary of the bisection is a[1]*b[1], the right boundary of the bisection is a[n]*b[n], and the judgment condition is the number larger than mid The number is not less than k.
ac code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e6 + 5;
int a[maxn], b[maxn], n, m;
ll k;
bool check(ll x){
int j = 1, sum = 0;
for(int i = n; i >= 1; i --){ //这里a降序遍历,如果a[i]*b[j]>=x,那么a[i+1]*b[j]肯定<x,a[i+1]*b[j-1]也肯定<x,因此这里的j没必要从头开始了
for(; j <= m; j ++){
if(1ll * a[i] * b[j] >= x){ //由于b是升序的,如果这里就大于等于x了,那么后面的所有j肯定都满足了,直接记录数量
sum += m - j + 1;
break;
}
}
}
return sum >= k;
}
int main(){
int t; scanf("%d",&t);
while(t --){
scanf("%d%d%lld",&n,&m,&k);
for(int i = 1; i <= n; i ++) scanf("%d", &a[i]);
for(int i = 1; i <= m; i ++) scanf("%d", &b[i]);
sort(a + 1, a + n + 1);
sort(b + 1, b + m + 1);
ll l = 1ll * a[1] * b[1], r = 1ll * a[n] * b[m], ans = -1;
while(l <= r){
ll mid = l + r >> 1;
if(check(mid)) l = mid + 1, ans = mid;
else r = mid - 1;
}
printf("%lld\n", ans);
}
return 0;
}