HDU 2141 Can you find it? (二分法)
Can you find it?
Time Limit:3000MS Memory Limit:10000KB 64bit IO Format:%I64d & %I64u
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
Sample Input
Sample Output
- 在二分查找之前,一定要对 A+B 数组进行排序
- 二分的退出条件:可以用for循环循环100次,可以达到 2100。如果那时找不到,则一定没有解了。
也可以在循环中:
while( front <= back )
{
......
if( F[mid] > Z ) back = mid - 1;
if(F[mid] < Z ) front = mid + 1;
......
......
}
#include <stdio.h> #include <string.h> #include <math.h> #include <algorithm> using namespace std; int ab[500*500+1]; int a[501],b[501],c[501]; int main() { int na,nb,nc,nx,i,j,kkk=0; int x; while(~scanf("%d%d%d",&na,&nb,&nc)) { for(i=0;i<na;i++) scanf("%d",&a[i]); for(i=0;i<nb;i++) scanf("%d",&b[i]); for(i=0;i<nc;i++) scanf("%d",&c[i]); int k=0,s,m,t; for(i=0;i<na;i++) for(j=0;j<nb;j++) ab[k++] = a[i] + b[j]; sort(ab,ab+na*nb); scanf("%d",&nx); int flag = 0; printf("Case %d:\n",++kkk); for(i=0;i<nx;i++) { scanf("%d",&x); for(j=0;j<nc;j++) { int x2; x2 = x - c[j]; flag = 0; s = 0; t = na * nb - 1; m = (s + t)/2; if(ab[m] == x2) flag = 1; while(s <= t) { if(ab[m] > x2) t = m-1; else s = m+1; m = (s + t)/2; //printf("s = %d t = %d\n",s,t); if(ab[m] == x2) { flag = 1; break; } } if(flag) { printf("YES\n"); break; } else continue; } if(!flag) printf("NO\n"); } } return 0; }