#1WA,刚接触二分

P2249 【深基13.例1】查找

silent_candle @ 2024-06-24 14:06:30

#include<bits/stdc++.h>
using namespace std;
int a[1000005];
int main()
{
    int n,m,t;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    scanf("%d",&a[i]);
    for(int i=1;i<=m;i++)
    {
        scanf("%d",&t);
        if(t<a[1])
        {
            printf("%d ",-1);
            continue;
        }
        if(t>a[n])
        {
            printf("%d ",-1);
            continue;
        }
        int l=1,r=n;
        while(l<=r)
        {
            int mid=(l+r)/2;
            if(a[mid]>=t)
            r=mid-1;
            else
            l=mid+1;
        }
        if(a[l-1]==t)
        printf("%d ",l-1);
        else if(a[l]==t)
        printf("%d ",l);
        else
        printf("%d ",-1);
    }
    return 0;
}

by chao_ti_jie @ 2024-06-24 14:08:37

#include<cstdio>
using namespace std;

int n,m,q,a[1000005];

int find(int x) 
{
    int l=1,r=n;
    while (l<r)
    {
        int mid=l+(r-l)/2;
        if (a[mid]>=x) 
        {
            r=mid;
        }
        else 
        {
            l=mid+1;
        }
    }

    if (a[l]==x) 
    {
        return l; 
    }
    else 
    {
        return -1;
    }
}

int main()
{
    scanf("%d %d",&n,&m);

    for (int i=1 ; i<=n ; i++)
    {
        scanf("%d",&a[i]);
    }

    for (int i=1 ; i<=m ; i++)
    {
        scanf("%d",&q);
        int ans=find(q);
        printf("%d ",ans);
    }

    return 0;
}

by Enmin @ 2024-07-05 20:28:00

#include <bits/stdc++.h>

using namespace std;
int n,m,a[1000100],b[100100];
int admin(int x) {
    int L=0,R=n+1;
    while(L+1<R) {
        int j=(L+R)/2;
        if(a[j]>=x) {
            R=j;
        }else {
            L=j;
        }
    }
    if(x!=a[R]) {
        return -1;
    }else {
        return R;
    }
}
int main() {
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) {
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=m;i++) {
        scanf("%d",&b[i]);
    }
    for(int i=1;i<=m;i++) {
        printf("%d ",admin(b[i]));
    }
    return 0;
}

by Konjac_C @ 2024-07-10 22:14:49

@silenta_candle 简单易懂

#include <bits/stdc++.h>
using namespace std;

int n,m;
unordered_map<int,int> mp;

int main()
{
    cin>>n>>m;
    int a;
    for(int i = 1;i <= n;i++){
        cin >> a;
        if( !mp[a] ) mp[a] = i;
    }
    while(m--){
        cin>>a;
        if( mp[a] ) cout << mp[a] << " ";
        else cout << -1 << " ";
    }
    return 0;
}

by Konjac_C @ 2024-07-10 22:16:33

@silenta_candle

这边建议用cin和cout,ios::sync_with_stdio(0);cin.tie(0),cout.tie(0);

方便且快


by Konjac_C @ 2024-07-10 22:19:47

int l=1,r=n,ans=0;
while(l<=r){
    int mid=l+r>>1;
    if(check(mid)) l=mid+1,ans=mid;
    else r=mid-1;
}
cout<<ans;

by silent_candle @ 2024-07-11 08:07:32

@Enmin 谢谢已关


by silent_candle @ 2024-07-11 08:07:52

@Konjac_C 谢谢已关


|