hrbeu.acm.1211Kth Largest 双重二分

http://acm.hrbeu.edu.cn/index.php?act=problem&id=1005&cid=74

Kth Largest

TimeLimit: 1 Second   MemoryLimit: 32 Megabyte 

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

解题思路
  双重二分。先对两个序列A,B从大到小排序,然后可以我们进行第一重二分:对要求取的答案二分,即求取的答案在[A[n]*B[n],A[1]*B[1]]之间,取s1=A[n]*B[n],e1=A[1]*B[1],mid=(s1+e1)/2,那么我们去计算在序列C中大于等于这个mid值的个数是多少,当然不是算出这个序列来,而是进行第二次二分。我们对于两个序列可以这样处理,枚举序列A,二分序列B,也就是说对于每个A[i],我们去二分序列B,来计算大于等于mid值的个数。那么我们可以得到结束条件,当大于等于mid值的个数大于等于k,且大于mid值的个数小于k,那么答案就是这个mid。那么时间复杂度就为n*log(n)*log(n^2)了。

View Code
#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxn 10010
int cases,n,a[maxn],b[maxn],ans,k,m,tt;
int cmp(const void *a,const void *b)
{
    return *(int *)b - *(int *)a;
}
void find(int s,int e,int t,int m)//查找小于t的数字
{
    int mid;
    while(s<=e)
    {
        mid=(s+e)>>1;
        if(m*b[mid]>t)
        {
            tt=mid;
            s=mid+1;
        }
        else e=mid-1;
    }
    return ;
}
int count(int t)
{
    int i,tp=0;
    for(i=1;i<=n;i++)
    {//枚举A中的每一个数字
        tt=0;
        find(1, n , t , a[i]);
        tp+=tt;
    }
    return tp;
}
void solve(int s,int e)

{
    int mid=(s+e)>>1,t1,t2;
    while(s<=e)
    {
        mid=(s+e)>>1;
        t1=count(mid);//统计大于mid值的个数
        t2=count(mid-1);//统计大于等于mid值的个数
        if( t1 < k && t2>=k)  { ans=mid; break; } //找到答案
        else if(t2<k) e=mid-1;
        else s=mid+1;
    }
    return ;
}

int main()
{
    int i,j;
    scanf("%d",&cases);
    while(cases--)    
    {
        scanf("%d%d",&n,&k);
        for (i = 1; i <= n; i++) scanf("%d", &a[i]);
        for (i = 1; i <= n; i++) scanf("%d", &b[i]);
        qsort(&a[1], n, sizeof(a[0]), cmp);
        qsort(&b[1], n, sizeof(b[0]), cmp);
        ans=0;
        solve(a[n] * b[n], a[1] * b[1]);
        printf("%d\n", ans);
    }
    return 0;
}

 

posted @ 2012-04-25 19:19  _sunshine  阅读(464)  评论(0)    收藏  举报