wanxuhang @ 2023-08-04 22:34:14
#include<bits/stdc++.h>
using namespace std;
long long a[1000005];
int f1(int left,int right,long long x){
if (left>right) return left;
int mid=(left+right)/2;
if (a[mid]==x) return f1(left,mid-1,x);
else if (a[mid]>x) return f1(left,mid-1,x);
else if (a[mid]<x) return f1(mid+1,right,x);
}
int main(){
int n,q;
cin>>n>>q;
for (int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for (int i=1;i<=q;i++){
long long x;
cin>>x;
int ans=f1(1,q,x);
if(x!=a[ans]) printf("-1 ");
else(printf("%d ",ans));
}
return 0;
}
by dfindsinfvidsnv @ 2023-08-05 14:59:22
mid不要-1吧,本蒟蒻也不太清楚
我的代码
#include<bits/stdc++.h>
using namespace std;
long long a[1000001],n,m,x;
int find(int x,int l,int r){
if(x==a[l])return l;
if(l>=r) return -1;
int mid=l+((r-l)>>1);
if(a[mid]>=x)return find(x,l,mid);
else return find(x,mid+1,r);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}while(m--){
cin>>x;
cout<<find(x,1,n)<<" ";
}
return 0;
}
by wanxuhang @ 2023-08-06 22:57:17
@yang_yi_bo 感谢,我再研究一下
by wo_hen_la @ 2023-08-07 11:40:55
@wanxuhang
最简单的代码
#include<bits/stdc++.h>
using namespace std;
map<long long,int> a;
int main()
{
long long n,m,b;
cin>>n>>m;
for(long long i=0;i<n;i++){
scanf("%d",&b);
if(a[b]==0){
a[b]=i+1;
}
}
while(m--){
scanf("%d",&b);
if(a[b]==0) printf("%d ",-1);
else printf("%d ",a[b]);
}
return 0;
}
by wanxuhang @ 2023-08-07 11:49:32
@wo_hen_la 感谢,我找到问题了