标签:二分查找 hdoj2141 can you find it
3 3 3 1 2 3 1 2 3 1 2 3 3 1 4 10
Case 1: NO YES NO
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; int a[250050],b[250050],c[250050],d[250050]; int main() { int A,B,C,i,j; int w=1; while(scanf("%d%d%d",&A,&B,&C)!=EOF) { int l=0; for(i=0;i<A;i++) scanf("%d",&a[i]); for(i=0;i<B;i++) scanf("%d",&b[i]); for(i=0;i<C;i++) scanf("%d",&c[i]); for(i=0;i<A;i++) for(j=0;j<B;j++) d[l++]=a[i]+b[j]; sort(d,d+l);//前两组相加并排序 sort(c,c+C); int n,m; printf("Case %d:\n",w++); scanf("%d",&n); while(n--) int y,t; int temp=0; scanf("%d",&m); for(i=0;i<C;i++) { y=m-c[i]; t=lower_bound(d,d+l,y)-d;//stl中找到大于或等于y的地址值,再减去首地址即得到数组所在下标 if(y==d[t])// /看该下标的值是否与y相等 { temp=1; break; } } if(temp==1) printf("YES\n"); else printf("NO\n"); } } return 0; }二分查找:
#include<iostream> #define MAX 251000 #include<algorithm> using namespace std; int L[MAX],N[MAX],M[MAX],a[MAX]; int main() { int l,n,m,cas=1; while(cin>>l>>n>>m) { int i,j,t,k; for(i=0;i<l;++i) cin>>L[i]; for(j=0;j<n;++j) cin>>N[j]; for(t=0;t<m;++t) cin>>M[t]; k=0; for(i=0;i<l;i++) for(j=0;j<n;++j) a[k++]=L[i]+N[j]; // cout<<" "<<k<<endl; sort(a,a+k); sort(M,M+m); cout<<"Case "<<cas++<<":"<<endl; int s,x,y,temp; cin>>s; while(s--) { temp=0; cin>>x; for(i=0;i<m;++i) { y=x-M[i]; int left,right,mid; left=0; right=k-1; if(a[k-1]<y) continue; while(left<=right) { // cout<<left<<" "<<right<<endl; mid=(left+right)/2; if(a[mid]==y) { temp=1; break; } if(a[mid]>y) right=mid-1; else left=mid+1; } } if(temp) cout<<"YES"<<endl; else cout<<"NO"<<endl; } } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:二分查找 hdoj2141 can you find it
原文地址:http://blog.csdn.net/zhangxiaoxiang123/article/details/47164635