求教
查看原帖
求教
931866
He_4002602楼主2023/7/12 11:17

为什么第一段全WA 第二段把mid改成l就AC了 第一段

#include <bits/stdc++.h>
using namespace std;
int main(){
	ios::sync_with_stdio(false);
    int n,m;
    cin>>n>>m;
    vector<int> a(n);
    
    for(int i=0;i<n;++i){
        cin>>a[i];
    }
    
    int t,l,r,mid;
    while(m--){
        cin>>t;
        l=0;r=n-1;
        while(l<=r){
            mid=(r+l)/2;
            if(a[mid]>=t)r=mid-1;
            else l=mid+1;
        }
        if(a[mid]==t)
        cout<<mid+1<<" ";
        else cout<<-1<<" ";
    }
    return 0;
}

第二段

#include <bits/stdc++.h>
using namespace std;
int main(){
	ios::sync_with_stdio(false);
    int n,m;
    cin>>n>>m;
    vector<int> a(n);
    
    for(int i=0;i<n;++i){
        cin>>a[i];
    }
    
    int t,l,r,mid;
    while(m--){
        cin>>t;
        l=0;r=n-1;
        while(l<=r){
            mid=(r+l)/2;
            if(a[mid]>=t)r=mid-1;
            else l=mid+1;
        }
        if(a[l]==t)
        cout<<l+1<<" ";//只有这两行不一样
        else cout<<-1<<" ";
    }
    return 0;
}
2023/7/12 11:17
加载中...