分析:二分,两边夹,细节见代码。(复杂度为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;
}