二分贪心专题C

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. 
InputThere 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. 
OutputFor 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

题目大意:给你三个数组A,B,C。问能不能再A,B,C数组中各找一个数使得他们的和为X里。

从数据范围来看A,B,C数组都不超过500个,但是暴力的话复杂度为n^3 空间与时间复杂度难以接受。

换个思路,将A,B数组合并为数组D,那么问题就变成了Di+Ci=X

即X-Di=Ci

枚举D数组中的元素并在C数组中进行二分查找。

依然是思路的问题。我们看到500^3难以接受,但是500*500很好实现,自己的榆木脑袋还是有待雕琢呀。。。

源代码:

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

int main()
{	
	int l,n,m,total=0;
	while (cin>>l>>n>>m)
	{
		total++;
		int tot=0,s;
		int a[505];int b[505];int c[505];int d[260000];
		for (int i=1;i<=l;i++) cin>>a[i];
		for (int i=1;i<=n;i++) cin>>b[i];
		for (int i=1;i<=m;i++) cin>>c[i];
		cin>>s;
		for (int i=1;i<=l;i++)
			for (int j=1;j<=n;j++) 
			{
				tot++;
				d[tot]=a[i]+b[j];
			}
		sort(d+1,d+tot+1);
		cout<<"Case "<<total<<":"<<endl;
		for (int i=1;i<=s;i++)
		{
			bool flag=false;
			int k;
			cin>>k;
			for (int j=1;j<=m;j++)
			{
				int l=1,r=tot,mid;
				int ans=k-c[j];
				while (l<=r)
				{
					mid=(l+r)/2;
					if (d[mid]==ans) 
					{
						flag=true;break;
					}
					if (d[mid]<ans) l=mid+1;
					if (d[mid]>ans) r=mid-1;
				}
				if (flag) break;
			}
			if (flag) cout<<"YES"<<endl;
			else cout<<"NO"<<endl;	
		}
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/ruozhalqy/article/details/54630449