问题描述 :
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.
输入:
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.
输出:
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.
样例输入:
3 3 3 1 2 3 1 2 3 1 2 3 3 1 4 10
样例输出:
Case 1: NO YESNO
问题分析:首先三重循环肯定会超时的,这个时候就应该用二分,然后二分的话是两项之和,所以三个数组要把其中两个数组的和的所有情况算出来并排序,然后输入x后枚举最后一个数组进行二分查询。
P.S:每次更新left和right的时候并不直接是mid,而是要+/- 1,否则就有可能无线循环
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; int flag; int a[510],b[510],c[510],x; int sum[510*510]; int t; void half(int num) { int left,right,mid; left = 0; right = t - 1; while(left <= right) { mid = (left + right) >> 1; if (sum[mid] + num >x) right = mid - 1; else if (sum[mid] + num < x) left = mid + 1; else { flag = 1; return ; } } } int main() { int l,n,m,s; int Count; Count = 1; while(~scanf("%d%d%d",&l,&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]; t = 0; for(int i=0; i<l; i++) for(int j=0; j<n; j++) sum[t++] = a[i] + b[j]; sort(sum,sum+t); cin >> s; printf("Case %d:\n",Count++); while(s--) { cin >> x; flag = 0; for(int i=0; i<m; i++) half(c[i]); if (flag) cout << "YES" << endl; else cout << "NO" << endl; } } return 0; }