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 Author wangye
思路:刚开始看到最大只有500,就算是三个循环,也应该不会超时吧 但还是太年轻。
又看了看大牛的思路,原来要用二分,平常用的不多,也就没想起来,尴尬。
我们只需要把前两个的值加在一起,再拿要计算的值减去他们的和,看能否在第三个数组中找到即可。
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; __int64 a[501], b[501], c[501]; __int64 sum[501*501]; __int64 L, N, M, t, len; int erfen(int x) { __int64 l = 0, r = len - 1; while(l <= r) { __int64 mid = (l + r)/2; if(sum[mid]==x) return 1; else if(sum[mid] > x) { r = mid - 1; } else { l = mid + 1; } } return 0; } int main() { __int64 Case = 1; while(~scanf("%I64d%I64d%I64d",&L,&N,&M)) { for(int i = 0; i < L; i++) scanf("%I64d",&a[i]); for(int i = 0; i < N; i++) scanf("%I64d",&b[i]); for(int j = 0; j < M; j++) scanf("%I64d",&c[j]); sort(c, c + M); len = 0; for(int i = 0; i < L; i++) { for(int j = 0; j < N; j++) { sum[len++] = a[i] + b[j]; } } __int64 p; sort(sum, sum + len); len = unique(sum, sum + len) - sum; ///unique是一个去重函数 返回值为去重后的最后一个元素的位置 scanf("%I64d",&t); printf("Case %I64d:\n",Case++); while(t--) { scanf("%I64d",&p); if(p > sum[len - 1] + c[M - 1]||p < sum[0] + c[0]) { printf("NO\n"); continue; } __int64 flag = 0; for(int j = 0; j < M; j++) { int k = p - c[j]; if(erfen(k)) { flag = 1; break; } } if(flag == 1) printf("YES\n"); else printf("NO\n"); } } return 0; }
