Can you find it? (二分) 2141

Can you find it?

Problem Description

Give you three sequences of numbers A, B, C, then we give you a number X. Now you need to calculate if you can find the three numbers Ai, Bj, Ck, which satisfy the formula Ai+Bj+Ck = X.

Input

There are many cases. Every data case is described as followed: In the first line there are three integers L, N, M, in the second line there are L integers represent the sequence A, in the third line there are N integers represent the sequences B, in the forth line there are M integers represent the sequence C. In the fifth line there is an integer S represents there are S integers X to be calculated. 1<=L, N, M<=500, 1<=S<=1000. all the integers are 32-integers.

Output

For each case, firstly you have to print the case number as the form "Case d:", then for the S queries, you calculate if the formula can be satisfied or not. If satisfied, you print "YES", otherwise print "NO".

Sample Input

 

3 3 3 1 2 3 1 2 3 1 2 3 3 1 4 10

Sample Output

 

Case 1: NO

             YES

             NO

第一种思路:

     两个for循环,对第三个数组进行二分,然后就Time Limit Exceeded

第二种思路:

   既然两个for循环会超时,那就一个for循环,先把两个数组的数加起来,虽然有点浪费空间,然后对这个相加得到的数组进行二分

#include<iostream>
#include<cstdio> 
#include<algorithm>
using namespace std;

int a[501];
int b[501];
int c[501];
int res[250001];
 
int main()
{
	
	int A,B,C,S,x;
	int len = 0;
	while(scanf("%d%d%d",&A,&B,&C) != EOF)
	{
		for(int i = 0;i < A;++i)
		   scanf("%d",&a[i]);
		for(int i = 0;i < B;++i)
		   scanf("%d",&b[i]);
		for(int i = 0;i < C;++i)
		   scanf("%d",&c[i]);
		scanf("%d",&S);
		len++;
		int index = 0;
		printf("Case %d:\n",len);
		
		for(int i = 0;i < A;++i)
		   for(int j = 0;j < B;++j)  //把两个数组内容加起来
		      res[index++] = a[i]+b[j];
		      
		sort(res,res+index);
		sort(c,c+C);
		for(int i = 0;i < S;++i)
		{
			scanf("%d",&x);
			int flag = 0;
			for(int j = 0;j < C;++j) 
			{
				int l = 0,r = index-1;
				while(r >= l)  //注意得加一个=,这里我们需要判断当l==r时,值是否等于x
				{
					int mid = (l+r)/2;
					if(c[j] + res[mid] == x)
					{
						flag = 1;break;
					}
					else if(c[j] + res[mid] < x)
					     l = mid+1;
					else if(c[j] + res[mid] > x)
					     r = mid-1;
				}
				
				if(flag)
				   break;
			}
			if(flag)
			   printf("YES\n");
			else
			   printf("NO\n");
		}
		  
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40511966/article/details/82956411