二分法--Can you find it?

来源:互联网 发布:怎么让淘宝号快速升3心 编辑:程序博客网 时间:2024/05/23 21:36
Give you three sequences of numbers A, B, C, then we giveyou a number X. Now you need to calculate if you can find the threenumbers Ai, Bj, Ck, which satisfy the formula Ai+Bj+Ck =X.
Input
There are many cases. Every data case is described asfollowed: In the first line there are three integers L, N, M, inthe second line there are L integers represent the sequence A, inthe third line there are N integers represent the sequences B, inthe forth line there are M integers represent the sequence C. Inthe fifth line there is an integer S represents there are Sintegers 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 asthe form "Case d:", then for the S queries, you calculate if theformula can be satisfied or not. If satisfied, you print "YES",otherwise print "NO".
Sample Input
3 3 31 2 31 2 31 2 331410
Sample Output
Case 1:NOYESNO



为避免MemoryExceed需要将三个数列中两个合并先计算,在由第三个数列的每一项逐一在新数列中二分查找对应项





#include
#include
using namespace std;
#define maxn 505
int A[maxn], B[maxn], C[maxn],AB[maxn*maxn];     //合并数组为maxn*maxn
int bs(int X, int n, int Ck)
{
 int m, a = 0, b = n - 1;
 while (a <= b)
 {
  m = (a + b) / 2;
  if (AB[m] + Ck == X) return1;           //==情况单独列出
  else if (AB[m] + Ck >X)
   b = m -1;
  else
   a = m +1;
 }
 return 0;
}
int main(){
 int L, N, M, S, X, cnt = 1;
 while (cin >> L){
  cin >> N >>M;
  for (int i = 0; i < L;i++){
   cin >>A[i];
  }
  for (int i = 0; i < N;i++){
   cin >>B[i];
  }
  for (int i = 0; i < M;i++){
   cin >>C[i];
  }
  int n = 0;
  for (int i = 0; i < L;i++)
  for (int j = 0; j < N;j++){              //求和合并数组
   AB[n++] =A[i] + B[j];
  }
  sort(AB, AB +n);                          //排序并去重,为二分查找做准备
  cin >> S;
  cout << "Case " <<cnt++ << ":" << endl;
  while (S--){
   cin >>X;
   int ans =0;
   for (int i =0; i < M; i++){
    if(bs(X, n, C[i])){
     ans= 1;
     cout<< "YES" << endl;
     break;
    }
   }
   if(!ans){
    cout<< "NO" << endl;
   }
  }
 }
 return 0;
}
0 0
原创粉丝点击