二分貪心專題C
阿新 • • 發佈:2018-11-11
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.
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 Input
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 Input
3 3 3 1 2 3 1 2 3 1 2 3 3 1 4 10
Sample Output
Case 1: NO YES NO
題目大意:給你三個陣列A,B,C。問能不能再A,B,C陣列中各找一個數使得他們的和為X裡。
從資料範圍來看A,B,C陣列都不超過500個,但是暴力的話複雜度為n^3 空間與時間複雜度難以接受。
換個思路,將A,B數組合併為陣列D,那麼問題就變成了Di+Ci=X
即X-Di=Ci
列舉D陣列中的元素並在C陣列中進行二分查詢。
依然是思路的問題。我們看到500^3難以接受,但是500*500很好實現,自己的榆木腦袋還是有待雕琢呀。。。
原始碼:
#include<iostream> #include <algorithm> using namespace std; int main() { int l,n,m,total=0; while (cin>>l>>n>>m) { total++; int tot=0,s; int a[505];int b[505];int c[505];int d[260000]; for (int i=1;i<=l;i++) cin>>a[i]; for (int i=1;i<=n;i++) cin>>b[i]; for (int i=1;i<=m;i++) cin>>c[i]; cin>>s; for (int i=1;i<=l;i++) for (int j=1;j<=n;j++) { tot++; d[tot]=a[i]+b[j]; } sort(d+1,d+tot+1); cout<<"Case "<<total<<":"<<endl; for (int i=1;i<=s;i++) { bool flag=false; int k; cin>>k; for (int j=1;j<=m;j++) { int l=1,r=tot,mid; int ans=k-c[j]; while (l<=r) { mid=(l+r)/2; if (d[mid]==ans) { flag=true;break; } if (d[mid]<ans) l=mid+1; if (d[mid]>ans) r=mid-1; } if (flag) break; } if (flag) cout<<"YES"<<endl; else cout<<"NO"<<endl; } } return 0; }