Can you find it?

问题描述 :

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.

输入:

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.

输出:

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.

样例输入:

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

样例输出:

Case 1:
NO
YES

NO

问题分析:首先三重循环肯定会超时的,这个时候就应该用二分,然后二分的话是两项之和,所以三个数组要把其中两个数组的和的所有情况算出来并排序,然后输入x后枚举最后一个数组进行二分查询。

P.S:每次更新left和right的时候并不直接是mid,而是要+/- 1,否则就有可能无线循环

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

int flag;
int a[510],b[510],c[510],x;
int sum[510*510];
int t;

void half(int num)
{
	int left,right,mid;
	
	left = 0;
	right = t - 1;
	

	while(left <= right)
	{
		mid = (left + right) >> 1;
		
		if (sum[mid] + num >x)
			right = mid - 1;	
		else if (sum[mid] + num < x)
			left = mid + 1;
		else
		{
			flag = 1;
			return ;
		}
	}
	
}

int main()
{
	int l,n,m,s;
	
	int Count;
	
	Count = 1;
	while(~scanf("%d%d%d",&l,&n,&m))
	{
		for(int i=0; i<l; i++)
			cin >> a[i];
		for(int i=0; i<n; i++)
			cin >> b[i];
		for(int i=0; i<m; i++)
			cin >> c[i];
		
		t = 0; 
		for(int i=0; i<l; i++)
			for(int j=0; j<n; j++)
				sum[t++] = a[i] + b[j];
		sort(sum,sum+t);	 
		
		cin >> s;
		printf("Case %d:\n",Count++);
		while(s--)
		{
			cin >> x;
			
			flag = 0;
			for(int i=0; i<m; i++)
				half(c[i]);

			
			if (flag)
				cout << "YES" << endl;
			else
				cout << "NO" << endl; 
		}
		
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值