Diary_Of_Young @ 2024-07-20 16:59:17
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int a[N],b[N];
int bsearch1(int a[],int l,int r,int p)
{
while(l<r)
{
int mid=(l+r)>>1;
if(a[mid]>=p)
{
r=mid;
}
else{
l=mid+1;
}
}
return l;
}
int bsearch2(int a[],int l,int r,int p)
{
while(l<r)
{
int mid=(l+r+1)>>1;
if(a[mid]<=p)
{
l=mid;
}
else{
r=mid-1;
}
}
return l;
}
int main()
{
int n;
int x;
std::ios::sync_with_stdio(false);
cin>>n>>x;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=1;i<=x;i++)
{
cin>>b[i];
}
for(int o=1;o<=x;o++)
{
int z=bsearch1(a,1,n,b[o]);
int g=bsearch2(a,1,n,b[o]);
if(a[z]!=a[g])
{
cout<<"-1 "<<endl;
continue;
}
cout<<z<<" ";
}
return 0;
}
by haimingbei @ 2024-07-20 17:02:06
@Diary_Of_Young
#include<bits/stdc++.h>
using namespace std;
int n,m,a[1000005],b[100005],t;
int two(int x){
int lt=1,rt=n;
while (lt<rt){
int mid=lt+(rt-lt)/2;
if (a[mid]>=x) rt=mid;
else lt=mid+1;
}
if (a[lt]==x) return lt;
else return -1;
}
int main(){
cin>>n>>m;
for (int i=1;i<=n;i++)cin>>a[i];
for (int i=1;i<=m;i++)cin>>b[i];
for(int i=1;i<=m;i++){
cout<<two(b[i])<<" ";
}
return 0;
}
我写的就那样,但是AC,你可以参考一下
by wuzhitong @ 2024-07-20 19:22:25
@Diary_Of_Young 我的代码:
#include<bits/stdc++.h>
using namespace std;
int a[1000001],k;
bool cheak(int i)
{
if(k<=a[i])return 0;
return 1;
}
int main()
{
int n,m;
cin>>n>>m;
//快读
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
for(int i=1;i<=n;i++)cin>>a[i];
while(m--)
{
cin>>k;
int l=1,r=n,ans;
while(l<=r)
{
int mid=(l+r)/2;
if(cheak(mid)==1)l=mid+1;
else r=mid-1,ans=mid;
}
if(a[ans]==k)cout<<ans<<" ";
else cout<<-1<<" ";
}
}
(求关 QWQ