传送门:点击打开链接
Can you find it?
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/10000 K (Java/Others)Total Submission(s): 35114 Accepted Submission(s): 8662
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
解题思路:a+b+c=X -> a+b=X-c,先处理出a+b所有可能的值,O(N^2),排序,O(NlogN),每次询问,枚举c,二分a+b,看是否存在a+b=X-c。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define MAXN 508
int L,N,M,T = 0,m,len;
long long n,a[MAXN],b[MAXN],c[MAXN],d[MAXN*MAXN];
int Binary_Search(long long x)
{
long long l = 1,r = len,mid;
while (l <= r)
{
mid = (l+r)/2;
if (d[mid] == x)
return 1;
if (d[mid] > x)
r = mid-1;
else if (d[mid] < x)
l = mid+1;
}
if (d[l] == x)
return 1;
return 0;
}
int main()
{
long long t,n;
while(~scanf("%d%d%d",&L,&N,&M))
{
len = 0;
for (int i = 1; i <= L; i++)
scanf("%lld", &a[i]);
for (int i = 1; i <= N; i++)
scanf("%lld", &b[i]);
for (int i = 1; i <= M; i++)
scanf("%lld", &c[i]);
for (int i = 1; i <= L; i++)
for (int j = 1; j <= N; j++)
d[++len] = a[i] + b[j];
sort(d+1,d+len+1);
printf("Case %d:\n", ++T);
scanf("%d", &m);
while (m--)
{
scanf("%lld",&n);
int flag = 0;
for (int i = 1; i <= M; i++)
{
if (Binary_Search(n-c[i]))
{
flag = 1;
break;
}
}
if (flag)
printf("YES\n");
else
printf("NO\n");
}
}
}
如果只有单个询问呢,我们有没有更简便的方法,其实我们可以O(N^2)完成。---two_pointer
对两个有序数组,可以在O(N)的情况下,判断是否存在a+b = X。
指针l指向A中最小的元素,指针r指向B中最大的元素。(A、B中实际元素下标从1开始)
若 A[l]+B[r] == X,找到和为X,返回;
若 A[l]+B[r] > X,r--;
若 A[l]+R[r] < X,l++;
直到 l > len(A) || r < 1 截止。A、B最多都只扫了一遍,所以复杂度为O(N)。