[HDU] [2141] Can you find it?

Problem Description

Loading...

Problem Analysis

Since N is at most 500
So if we use triple nested loops to check, it will time out
Then we can think about how to optimize

Ai+Bj+Ck=X
⇒
Ai+Bj=X-Ck

So we can preprocess Ai+Bj
After saving them, sort them
Then for each query
loop over C and then in the preprocessed results
use Binary Search to find whether X-Ck exists

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<stdio.h>
#include<algorithm>
using namespace std;
int l,n,m,cnt;
int a[520],b[520],c[520],res[520*520];
bool find(int x) {
	int l=0,r=cnt-1;
	while(l<=r) {
		int mid=(l+r)/2;
		if(res[mid]>x)
			r=mid-1;
		else if(res[mid]<x)
			l=mid+1;
		else
			return true;
	}
	return false;
}
int main() {
	int kase=0;
	while(scanf("%d %d %d",&l,&n,&m)!=EOF) {
		printf("Case %d:\n",++kase);
		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]);
		cnt=0;
		for(int i=0; i<l; i++)
			for(int j=0; j<n; j++)
				res[cnt++]=a[i]+b[j];
		sort(res,res+cnt);
		int T;
		scanf("%d",&T);
		while(T--) {
			int t;
			scanf("%d",&t);
			int i;
			for(i=0; i<m; i++) {
				if(find(t-c[i]))
					break;
			}
			if(i<m)
				printf("YES\n");
			else
				printf("NO\n");
		}
	}
	return 0;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...