Can you find it?
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/10000 K (Java/Others)
Total Submission(s): 17937 Accepted Submission(s): 4526
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
题意: 给你 3 个数组,要求 能否 从这3个数组中 各 选择一个数使得三个数的和为 s
直接暴力,超时, 要用 二分,首先要将其中的两个合并,在进行二分查找AC
已AC代码:(二分法)
#include<cstdio>
#include<algorithm>
#define MAX 251000
using namespace std;
int G[MAX];
int A[600],B[600],C[600];
int L,N,M,S;
int main()
{
int i,j,K,Cas=1;
while(scanf("%d%d%d",&L,&N,&M)!=EOF)
{
for(i=0;i<L;++i)
scanf("%d",&A[i]);
for(i=0;i<N;++i)
scanf("%d",&B[i]);
for(i=0;i<M;++i)
scanf("%d",&C[i]);
K=0;
for(i=0;i<L;++i) // 先将其中的两个加一起
for(j=0;j<N;++j)
G[K++]=A[i]+B[j];
sort(G,G+K); // 一定要排序(二分必须排序)
sort(C,C+M);
printf("Case %d:\n",Cas++);
scanf("%d",&S);
while(S--)
{
int y,x,flag=0;
scanf("%d",&x);
for(i=0;i<M;++i)
{
y=x-C[i];
int mid,left=0,right=K-1;
if(G[K-1]<y) // 若 G 中最大的小于 y 不用再查找了
continue;
while(right>=left) // 二分 (二分的是坐标 )
{
mid=(left+right)/2;
if(G[mid]==y)
{
flag=1;
break;
}
if(G[mid]>y)
right=mid-1;
else
left=mid+1;
}
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
STL t = lower_bound(G,G+K,y)-G; 返回值第一个大于等于 y 的数的 地址 ,G 是一个有序数组,K 为其长度,要减 G 得第一个大于等于 y 的数的下标
#include<cstdio>
#include<algorithm>
#define MAX 251000
using namespace std;
int G[MAX];
int A[600],B[600],C[600];
int L,N,M,S;
int main()
{
int i,j,K,Cas=1;
while(scanf("%d%d%d",&L,&N,&M)!=EOF)
{
for(i=0;i<L;++i)
scanf("%d",&A[i]);
for(i=0;i<N;++i)
scanf("%d",&B[i]);
for(i=0;i<M;++i)
scanf("%d",&C[i]);
K=0;
for(i=0;i<L;++i)
for(j=0;j<N;++j)
G[K++]=A[i]+B[j];
sort(G,G+K);
sort(C,C+M);
printf("Case %d:\n",Cas++);
scanf("%d",&S);
while(S--)
{
int y,x,flag=0;
scanf("%d",&x);
for(i=0;i<M;++i)
{
y=x-C[i];
int t;
t=lower_bound(G,G+K,y)-G;
if(G[t]==y)
{
flag=1;
break;
}
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}