求助大佬 这个二分有什么问题嘛

P1678 烦恼的高考志愿

Gent7c @ 2024-03-13 16:17:28

#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
long long n, m;
const int N = 1e5 + 5;
int a[N];
int l, r;
int sum = 0;
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> a[i];
    sort(a + 1, a + 1 + n);
    int x;
    l = 0, r = n + 1;
    while (m--)
    {
        int x;
        cin >> x;
        while (l +1!= r)
        {
            int mid = (r + l) >> 1;
            if (a[mid] >= x) r = mid;
            else l = mid;
        }
        sum += min(abs(a[l] - x), abs(a[l + 1] - x));
    }
    cout << sum;
}

by xyx404 @ 2024-03-16 15:00:24

@Gent7c

#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
long long n, m;
const long long N = 1e5 + 5;
long long a[N];
long long l, r;
long long sum = 0;
int main()
{
    cin >> n >> m;
    for (long long i = 1; i <= n; i++) cin >> a[i];
    sort(a + 1, a + 1 + n);
    long long x;
    //换地方 
    while (m--)
    {   
        l = 1, r = n ;//换地方 
        long long x;
        cin >> x;
        long long minn=1000010;//加 
        while (l<=r)
        {
            long long mid = (r + l) >> 1;
            minn=min(minn,abs(a[mid]-x));//加 
            if (a[mid] >= x) r = mid-1;//改 
            else l = mid+1;//改 
        }
        sum+=minn;//改 
    }
    cout << sum;
}

|