题目:
Kth Largest
TimeLimit: 1 Second MemoryLimit: 32 Megabyte
Totalsubmit: 442 Accepted: 161
Description
There are two sequences A and B with N (1<=N<=10000) elements each. All of the elements are positive integers. Given C=A*B, where '*' representing Cartesian product, c = a*b, where c belonging to C, a belonging to A and b belonging to B. Your job is to find the K'th largest element in C, where K begins with 1.
Input
Input file contains multiple test cases. The first line is the number of test cases. There are three lines in each test case. The first line of each case contains two integers N and K, then the second line represents elements in A and the following line represents elements in B. All integers are positive and no more than 10000. K may be more than 10000.
Output
For each case output the K'th largest number.
Sample Input
2
2 1
3 4
5 6
2 3
2 1
4 8
Sample Output
24
8
使用两次二分
第一次十分枚举第K大数,第二次二分判该第K大数合法性,根据是否有K-1个数比它小
源代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a>b;
}
int find(int mid,int a[],int b[],int n)
{
int res=0;
int l=0;
int r=n-1;
for(int i=0;i<n;i++)
{
l=0;
r=n-1;
while(l<=r)
{
int m=(l+r)/2;
if(a[i]*b[m]>=mid)
{
l=m+1;
}
else
{
r=m-1;
}
}
res+=l;
}
return res;
}
int main()
{
int a[10010];
int b[10010];
int t;
scanf("%d",&t);
while(t--)
{
int n,k;
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(int i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
sort(a,a+n,cmp);
sort(b,b+n,cmp);
int left=a[0]*b[0];
int right=a[n-1]*b[n-1];
int m;
int res;
while(left>=right)
{
int middle=(left+right)/2;
m=find(middle,a,b,n);
//printf("middle m: %d %d\n",middle,m);
if(m<k)
{
left=middle-1;
}
else
{
if(find(middle+1,a,b,n)<k)
{
res=middle;
break;
}
else
{
right=middle+1;
}
}
} printf("%d\n",res);
}
return 0;
}