Can you find it? HDU-2141 (二分查找模版题)

3 篇文章 0 订阅

总结

  • 思路

这个神奇的题WA了8次,折在了各种奇葩的问题上,其实就是标准的二分查找模版题

大数暴力会爆炸,枚举三个数组,时间复杂度O(N^3)。

解决的方法是进行预处理操作。将本来同时进行,多层循环中的某些层拉出来,分部操作。首先将前两个数组进行枚举得到和数组,时间复杂度O(n^2),然后枚举第三个数组,在和数组中找值,查找为了节省时间,选用二分。

  • 错误

首先是vector的使用,刚开始接触,就觉得很好用,除了可以当成数组一样用之外还有很多附加的函数,但是若使用push_back操作来代替数组中的赋值要注意,对于多组数据测试来说,每组数据要记得清空vector。

WA的错误还有一次是超内存,开始以为是因为long long 500*500的原因,其实这个是不会超的,超的原因是初始化为0的错写在了多组数据循环的外面,这样不断测试之后后面数组就越开越大。


 

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 


代码

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int a[505],b[505],c[505]; 
vector<int> d;
int main(void)
{
	int l,n,m,s;
	int T = 0;
	while(scanf("%d%d%d",&l,&n,&m)!=EOF)
	{
		d.clear();//用vector记得清空 
		printf("Case %d:\n",++T);
		for(int i = 0;i<l;i++) scanf("%d",&a[i]);
		for(int i = 0;i<n;i++) scanf("%d",&b[i]);
		for(int i = 0;i<m;i++) scanf("%d",&c[i]);
		for(int i = 0;i<l;i++)
		{
			for(int j = 0;j<n;j++)
			{
				d.push_back(a[i]+b[j]);
			}	
		}		
		sort(d.begin(),d.end());
		scanf("%d",&s);
		int x;
		while(s--)
		{
			int flag = 0;
			scanf("%d",&x);
			for(int i = 0;i<m;i++)
			{
				int left = 0,right = d.size()-1,mid;
				while(left<=right)
				{
					mid = (left+right)/2;
					if(d[mid]==x-c[i]) 
					{
						flag = 1;
						break;
					}
					else if(d[mid]<x-c[i]) left = mid+1;
					else right = mid-1;
				}				
			}
			if(flag) printf("YES\n");
			else printf("NO\n");						
		}		
	}	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值