90求大佬看看哪里有问题

P1678 烦恼的高考志愿

z3292600300 @ 2024-07-19 15:04:05

#include <iostream>
#include<iomanip>
#include<algorithm>
using namespace std;
int main()
{
    long long m, n;
    cin >> m >> n;
    long long* sch = new long long[m];
    for (long long i = 0; i < m; i++) {
        cin >> sch[i];
    }
    sort(sch , sch + m);
    unsigned long long ans = 0;
    for (long long i = 0; i < n; i++) {
        long long num;
        cin >> num;
        long long left ;

        long long right = lower_bound(sch , sch + m, num) - sch;
        if (right == 0) {
            ans += sch[right] - num;
            continue;
        }
        else left = right - 1;
        if (sch[left] + sch[right] - num * 2 > 0) {
            ans += num - sch[left];
        }
        else {

            ans += sch[right] - num;
        }
    }
    cout << ans;
}

by fanhaoxuan0110 @ 2024-07-25 11:15:13

@z3292600300 包100的呀?

#include<bits/stdc++.h>
using namespace std;
int a[100100],b[100100];
int main()
{
    int 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];
    }
    sort(a+1,a+n+1);
    int s=0;
    for(int i=1; i<=m; i++)
    {
        int l=0,r=n+1;
        while(l<r)
        {
            int mid=(l+r)/2;
            if(a[mid]<=b[i])
            {
                l=mid+1;
            }
            else
            {
                r=mid;
            }
        }
        if(b[i]<=a[1])
        {
            s+=a[1]-b[i];
        }
        else
        {
            s+=min(abs(a[l-1]-b[i]),abs(a[l]-b[i]));//加上两个绝对值中最小
        }
    }
    cout<<s;
    return 0;
}

by amd47802574 @ 2024-07-28 09:45:13

没有判断最后一个元素,lower_bound找不到时就会返回数组长度

for (int i = 0; i < n; i++) {
    int idx = lower_bound(a.begin(), a.end(), b[i]) - a.begin();//返回下标
    if (idx == 0) ans += a[0] - b[i];//第一个
    else if (idx == m) ans += b[i] - a[m-1];//(最后一个)找不到
    else ans += min(a[idx] - b[i], b[i] - a[idx - 1]);//找到了
}

|