xdu 1068 Clinton’s beliefs

题目

两个数组,求所有乘积中的第k大的。

方法:二分。


#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
typedef long long LL;
#define N 10001
LL n1,n2, k, a[N], b[N], flag;

LL cal(LL num)
{
	LL i, j, ans;
	if(a[n1-1]*b[n2-1]<=num)
		return 0;
	j = n2-1;
	ans = 0;
	for(i=0; i<n1; i++)
	{
		for(; j>=0 && a[i]*b[j]>num; j--);
		ans += n2-1-j;
	}
	return ans;
}

LL solve()
{
	LL l, r, mid, tmp;
	l=a[0]*b[0], r=a[n1-1]*b[n2-1];
	while(l<=r)
	{
		flag = 0;
		mid = (l+r)>>1;
		tmp = cal(mid);
		if(tmp>=k) l = mid+1;
		else r = mid-1;
	}
	return r+1;
}

int main()
{
	int i, j, t;
	scanf("%d", &t);
	while(t--)
	{
		scanf("%lld%lld%lld", &n1,&n2,&k);
		for(i=0; i<n1; i++) scanf("%lld", &a[i]);
		for(i=0; i<n2; i++) scanf("%lld", &b[i]);
		sort(a, a+n1);
		sort(b, b+n2);
		printf("%lld\n", solve());
	}
	return 0;
}

你可能感兴趣的:(xdu 1068 Clinton’s beliefs)