Frank123123123 @ 2024-08-28 14:24:05
#include<bits/stdc++.h>
using namespace std;
int main(){
int m,n;
cin>>m>>n;
int a[1000010]={0};
for(int i=1;i<=m;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
int q;
cin>>q;
int l=1,r=m;
while(l<r){
int mid=(l+r)/2;
if(a[mid]<q){
l=mid+1;
}
else if(a[mid]>q){
r=mid;
}
else{
l=mid;
}
}
if(a[l]==q){
cout<<l;
}
else{
cout<<-1;
}
}
return 0;
}
怎么办
by Frank123123123 @ 2024-08-28 14:26:13
我初学二分
by 违规用户名Jx9)zIu @ 2024-08-28 14:27:49
#include<bits/stdc++.h>
using namespace std;
long long a[1000005];
int main(){
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=m;i++){
int q;
cin>>q;
int l=1,r=n,mid;
while(l<r){
mid=(l+r)/2;
if(a[mid]>=q){
r=mid;
}else{
l=mid+1;
}
}
if(a[l]==q){
cout<<l<<" ";
}else{
cout<<-1<<" ";
}
}
return 0;
}
by Y204335 @ 2024-08-28 14:28:00
@Frank123123123 变量开全局,别开局部,开局部爆空间了
by 违规用户名Jx9)zIu @ 2024-08-28 14:28:26
@Frank123123123
求关
by ZengZeng_xy @ 2024-08-28 15:05:01
变量开全局,这样变量默认初值为零,不用初始化。
二分里面加上q==a[mid]的情况
by ZengZeng_xy @ 2024-08-28 15:08:36
like this
#include<bits/stdc++.h>
using namespace std;
int a[1000010];
int m,n;
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];
}
for(int i=1;i<=m;i++){
int q;
cin>>q;
int l=1,r=n;
while(l<r){
int mid=l+r>>1;
if(a[mid] == q){
r=mid;
}
else if(a[mid]<q){
l=mid+1;continue;
}
else if(a[mid]>q){
r=mid-1;continue;
}
//cout<<l<<' '<<r<<'\n';
}
if(a[l]==q){
cout<<l<<' ';
}
else{
cout<<-1<<' ';
}
}
return 0;
}
by ZengZeng_xy @ 2024-08-28 15:12:42
@Frank123123123 点个关注呗(喜
by Frank123123123 @ 2024-08-28 15:22:34
@ZengZeng_xy\ 已关