Bean233 @ 2023-04-14 16:47:21
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n,m;
cin >> n >> m;
int a[n+100];
for(int i=1;i<=n;i++) {
scanf("%d",&a[i]);
}
for(int i=1;i<=m;i++) {
int q;//1 1 2 3 5
scanf("%d",&q); //3
int l=1,r=n,mid=(l+n)/2;
while(l<r) {
int p=0;
if(q==a[l]) {
cout << l << " ";
break;
}else if(q==a[r]) {
for(int i=r;i>=1;i--) {
if(a[i]!=q) {
cout << i+1 << " ";
p=1;
break;
}
}
break;
} else if(q>a[mid]) {
l = mid;
}else if(q<a[mid]) {
r = mid;
}else if(q==a[mid]) {
for(int i=mid;i>=1;i--) {
if(a[i]!=q) {
cout << i+1 << " ";
p=1;
break;
}
}
}
if(p==1) {
break;
}
mid = (l+r)/2;
if(mid==r||mid==l) {
cout << -1 << " ";
break;
}
}
}
return 0;
}
RT
by _zhx @ 2023-04-14 17:19:42
推荐vector
using namespace std;
multiset<int>w; //自动排序
vector<int>v;
int main() {
int n,m;
scanf("%d%d",&n,&m);//输入n,m
for(int i=0;i<n;i++)
{
int x;
scanf("%d",&x);//输入x
v.push_back(x);//将x插入v
}
while(m--)
{
int x;
scanf("%d",&x);
int t=lower_bound(begin(v),end(v),x)-v.begin()+1;// (有点长,自己搜吧,因为我很懒)
if(v[t-1]==x) cout<<t<<" "; //输出t
else cout<<"-1 ";
}
return 0;
}