mndogdied @ 2024-08-12 21:17:06
#include<bits/stdc++.h>
using namespace std;
int a,b,d;
int c;
struct C
{
int num,st;
}r[1000002];
int Eggboss(int x)
{
int l=0,rr=c+1;
r[l].num=INT_MIN;
r[rr].num=INT_MAX;
while(l+1<rr)
{
int m=(l+rr)/2;
if(r[m].num>x) rr=m;
else if(r[m].num<x) l=m;
else return r[m].st;
}
return -1;
}
signed main()
{
r[1].num=-1;
r[1].st=-1;
cin>>a>>b;
for(int i=1;i<=a;i++)
{
int s;
cin>>s;
if(s!=r[c].num)
{
c++;
r[c].num=s;
r[c].st=i;
}
}
// if(c==0) c=1;
for(int i=1;i<=b;i++)
{
cin>>d;
cout<<Eggboss(d)<<' ';
}
return 0;
}
by liruizhou_lihui @ 2024-08-12 21:22:22
while(l+1<rr)写成while(l<=rr)
rr=m写成rr=m-1
l=m写成 l=m+1
还有建议m写成mid这样你的程序更有可读性
by liruizhou_lihui @ 2024-08-12 21:24:31
求关
你可以拿我的对一下
//#include<bits/stdc++.h>
#include<iostream>
#include<math.h>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int N=1e6 +1;
int a[N];
int n,x,m;
int main()
{
//ios::sync_with_stdio(false),cin.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=0;i<m;i++)
{
cin>>x;
int ans=-1;
int l=1,r=n,mid;
while(l<=r)
{
mid=(l+r)/2;
if(x<a[mid])r=mid-1;
else if(x>a[mid])l=mid+1;
else
{
ans=mid;
r=mid-1;
}
}
cout<<ans<<' ';
}
return 0;
}