求助

P2249 【深基13.例1】查找

mobei1234 @ 2023-12-23 21:10:24

//为啥WA

#include <bits/stdc++.h>

using namespace std;

long long a[1000005], b[1000005];

void f(int x, int n) {

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

      }

      if (cnt != 0) {
          cout << ans << " ";
      } else {
          cout << -1;
      }
}

int main() {

      long long n, m;
      cin >> n >> m;
      for (int i = 1; i <= n; i++) {
          cin >> a[i];
      }
      for (int i = 1; i <= m; i++) {
          cin >> b[i];
      }

      for (int i = 1; i <= m; i++) {
          f( b[i], n);
      }
      return 0;
}

by OIerWu_829 @ 2023-12-23 21:12:21

@wwz1234

输出少了空格。


by OIerWu_829 @ 2023-12-23 21:12:54

@wwz1234

亲测改后能 AC。

求关 QwQ。


by mobei1234 @ 2023-12-23 21:17:39

@wzj0829 ok


by timmyliao @ 2024-01-01 08:17:28

@wwz1234 AC(经供参考):

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

|