二分经典题
Problem DescriptionGive 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.InputThere 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.OutputFor 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 Input3 3 3 1 2 3 1 2 3 1 2 3 3 1 4 10
Sample Output
Case 1: NO YES NO 先暴力求解出所有 Ai + Bj,然后二分查找 X – Ck 时间复杂度就是O(n^2logn)。 代码#include <cstdio> #include <iostream> #include <cmath> #include <cstring> #include <cstdlib> #include <string> #include <queue> #include <vector> #include <stack> #include <algorithm> using namespace std; #define MAXN 505 long long A[MAXN],B[MAXN],C[MAXN],S[MANX*MAXN]; int num; bool search(long long p) { int l=0,r=num-1; int mid; while (r>=l) { mid=(r+l)/2; if (S[mid]==p) return true; else if(S[mid]<p) l=mid+1; else r=mid-1; } return 0; } int main () { int L,M,N,s,ca=0; long long x; int i,j; while (scanf ("%d%d%d",&L,&M,&N)!=EOF) { for (i=0;i<L;i++) scanf ("%I64d",&A[i]); for (i=0;i<M;i++) scanf ("%I64d",&B[i]); for (i=0;i<N;i++) scanf ("%I64d",&C[i]); num=0; for (i=0;i<L;i++) for (j=0;j<M;j++) S[num++]=A[i]+B[j]; sort (S,S+num); sort (C,C+N); scanf ("%d",&s); printf ("Case %d:\n",++ca); while (s--) { scanf ("%I64d",&x); if(x<S[0]+C[0]||x>S[num-1]+C[N-1]) { printf ("NO\n"); } else { int mm; for (mm=0;mm<N;mm++) { long long p=x-C[mm]; if(search(p)) { printf ("YES\n"); break; } } if(mm==L) printf ("NO\n"); } } } return 0; }