2020.4.18算法题
1.
#include<iostream> using namespace std; int n,l; bool flag; int k[50]; int main(){ cin>>n>>l; for(int i=1;i<=n;i++){ cin>>k[i]; } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ for(int o=1;o<=n;o++){ for(int m=1;m<=n;m++){ if(k[i]+k[j]+k[o]+k[m] == l){ flag=1; } } } } } if(flag){ cout<<"Yes!"<<endl; }else{ cout<<"No!"<<endl; } return 0; }
优化:二分查找讲原先的O(N^4)优化成O(N^3)log(N)
#include<iostream> #include<algorithm> using namespace std; int n,m,data[50]; int f,left,right; bool bisearch(int number){ int l=1; int r=n; int mid; while(l<=r){ mid=(l+r)/2; cout<<l<<' '<<r<<' '<<mid<<endl; if(data[mid] == number){ return true; } else if(number>data[mid]){ l=mid+1; }else{ r=mid-1; } } return false; } int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ cin>>data[i]; } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ for(int k=1;k<n;k++){ if(bisearch(m-data[i]-data[j]-data[k])){ f=1; } } } } if(f){ cout<<"Yes"<<endl; }else{ cout<<"No"<<endl; } return 0; }
再次优化,将内2层所有可能保存在一个数组中,然后对该数组进行二分查找,讲复杂度降到O(N^2logN)
#include<iostream> using namespace std; int n,m,k[50],a[50]; bool t; void quicksort(int x,int y){ int base=k[x]; int left=x; int right=y; while(x!=y){ if(x>y){ return; } while(k[y] >=base && x<y){ y--; } while(k[x] <= base && x<y){ x++; } int temp=k[x]; k[x]=k[y]; k[y]=temp; } int t=k[left]; k[left]=k[x]; k[x]=t; quicksort(left,x-1); quicksort(x+1,right); } bool binarysearch(int x){ int left=1; int right=n; while(left<right){ int mid=(left+right)/2; if(k[mid] == x){ return true; } else if(x>k[mid]){ left=mid+1; } else{ right=mid-1; } } return false; } int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ cin>>a[i]; } for(int c=1;c<=n;c++){ for(int d=1;d<=n;d++){ k[(c-1)*n+d]=a[c]+a[d]; } } quicksort(1,n*n); for(int e=1;e<=n;e++){ for(int b=1;b<=n;b++){ int d=m-a[e]-a[b]; if(binarysearch(d)){ t=true; } } } if(t){ cout<<"Yes"<<endl; }else{ cout<<"No"<<endl; } return 0; }
2.
#include<iostream> using namespace std; int n,ans; int num[50]; int f; void solve(){ for(int i=1;i<=n;i++){ for(int j=i+1;j<=n;j++){ for(int k=j+1;k<=n;k++){ int longest=max(num[i],max(num[j],num[k])); int sum=num[i]+num[j]+num[k]; int left=sum-longest; if(left>longest){ ans=max(ans,sum); f=1; } } } } } int main(){ cin>>n; for(int i=1;i<=n;i++){ cin>>num[i]; } solve(); if(f){ cout<<ans<<endl; }else{ cout<<0; } return 0; }
3.
#include<iostream> using namespace std; int L,n; int x[50]; int longest,shortest; int main(){ cin>>L>>n; for(int i=1;i<=n;i++){ cin>>x[i]; } for(int i=1;i<=n;i++){ longest=max(longest,max(x[i],L-x[i])); shortest=max(shortest,min(x[i],L-x[i])); } cout<<"max time:"<<longest<<' '<<"min time:"<<shortest<<endl; return 0; }