ZHB666include @ 2024-12-01 13:08:52
题目:P2249 【深基13.例1】查找
代码:
#include<bits/stdc++.h>
using namespace std;
long long n,m,a[1000000],x,t;
int cz(int t,int w,int x){
while(t<=w){
int mid=(t+w)/2;
if(a[mid]>=x){
w=mid-1;
}else{
t=mid+1;
}
}
if(t>n) return -1;
if(a[t]!=x) return -1;
return t;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<=m;i++){
scanf("%d",&x);
printf("%d ",cz(1,n,x));
}
return 0;
}
大佬们帮我康康吧,Thank you!
by PengRuiXuan @ 2024-12-01 13:15:07
#include <bits/stdc++.h>
using namespace std;
int a[1000010],n,m,q; // 1e6+10
int bsearch(int l,int r,int x)
{
while(l<r)
{
int mid=l+(r-l)/2;
if(a[mid]>=x)
{
r=mid;
}
else
{
l=mid+1;
}
}
if(a[l]==x)
{
return l;
}
return -1;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
while(m--)
{
cin>>q;
cout<<bsearch(1,n,q)<<" ";
}
return 0;
}
by xuruize666 @ 2024-12-01 13:16:49
算法标签:
二分
Why do you use bruid algorithm? (为什么你用暴力算法?)
by stickfigures @ 2024-12-01 13:48:36
用二分,不用暴力,如果过不了再加上上面的代码(毫秒优化器
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
)
by ZHB666include @ 2024-12-14 10:38:43
了解,谢谢!!!