~欢迎你!第 AmazingCounters.com 位造访者

ACM: 限时训练题解-Runtime Error-二分查找

  1. Runtime Error

 

Bahosain was trying to solve this simple problem, but he got a Runtime Error on one of the test cases, can you help him by solving it?

 

Given an array of N non-negative integers and an integer K, your task is to find two integers X and Y from the given array such that X × Y = K.

The chosen numbers must have different indices in the   array.

 

Input

 

The first line of input contains T (1 ≤ T ≤ 128), the number of test   cases.

 

The first line of each test case contains two integers: N (2 ≤ N ≤ 100,000) and K (1 ≤ K ≤ 100,000). The next line contains N space-separated integers, each between 0 and   100,000.

Output

 

For each test case, if there is no solution, print -1 on a single line. Otherwise print a single line with two space-separated integers X Y (X ≤   Y), where X and Y are two numbers from the given array and X × Y = K.

If there is more than one possible solution, print the one with the minimum   X.

 

 

 

Sample Input

Sample Output

4

 

 

2 6

6 12

 

 

-1

3 6 2

4 2

9

3 12

2 1

 

 

1 12

1 2

 

 

 

4 36

 

 

 

12 18

3 36

 

 

4 12

 

 

 

1 2 6

12

 

 

 

/*
题意:
从给出的N个数中找出两个数,乘积为 K;

枚举x 二分搜索 y  
*/ 

#include"iostream"
#include"algorithm"
#include"cstdio"
#include"cstring"
#include"cmath"
#define MX 100000 + 50
using namespace std;

int a[MX];

int main() {
	int T,k,n;
	scanf("%d",&T);
	while(T--) {
		scanf("%d%d",&n,&k);
		for(int i=0; i<n; i++) {
			scanf("%d",&a[i]);
		}
		sort(a,a+n);
		int ans1=0,ans=0;
		for(int i=0; i<n-1; i++) {
			ans1=i;
			
			int l=i+1,r=n-1,mid;
			while(l<=r) {
				mid=(r+l)/2;
				if(a[i]*a[mid]>k) {
					r=mid-1;
				} else if(a[i]*a[mid]<k) {
					l=mid+1;
				} else if(a[i]*a[mid]==k){
					ans=mid;
					break;
				}
			}
			if(ans)break;
			
		}
		if(ans)
			printf("%d %d\n",a[ans1],a[ans]);
		else printf("-1\n");
	}
	return 0;
}

  

posted @ 2016-07-27 00:26  ~HDMaxfun  阅读(580)  评论(0编辑  收藏  举报