P2249 查找 求条

题目总版

I_am_zcr @ 2024-11-24 11:26:47

用的二分,结果0分,求调

原题

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n,m,a[100005];
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    while(m--){
        int l=1,r=n,mid,t,ans;
        cin>>t;
        while(l<=r){
            mid = (l+r)/2;
            if(t<=a[mid]){
                r=mid-1;
                ans=mid;
            }
            else  l=mid+1;
        }
        if(a[ans]==t) cout<<ans<<' ';
        else cout<<-1;
    } 

    return 0;
} 

by HZHDCM @ 2024-11-24 11:39:39

-1后面的空格?@I_am_zcr


by I_am_zcr @ 2024-11-24 11:40:23

@HZHDCM 恍然大悟,不过还有一个RE


by I_am_zcr @ 2024-11-24 11:56:10

救命啊,加空格后全都RE了,自测也没问题呀


by HZHDCM @ 2024-11-24 11:59:13

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n,m,a[1000005];
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    while(m--){
        int l=1,r=n,mid,t,ans=1;
        cin>>t;
        while(l<=r){
            mid = (l+r)/2;
            if(t<=a[mid]){
                r=mid-1;
                ans=mid;
            }
            else  l=mid+1;
        }
        if(a[ans]==t) cout<<ans<<' ';
        else cout<<-1<<' ';
    } 

    return 0;
} 

@I_am_zcr 空间开小了,而且ans可能没有更新到,应该赋为1


by I_am_zcr @ 2024-11-24 12:07:52

@HZHDCM 谢谢,我想的是1000005,结果开了个100005


|