求助!!!开了longlong还是没过最后一个测试点

P1678 烦恼的高考志愿

Mrlaolu @ 2023-09-30 21:15:29

//
// Created by COLORFUL on 2023/9/30.
//
#include "bits/stdc++.h"
#define int long long

using namespace std;
int a[100020000] = {0},b[100020000] = {0};

signed main()
{
    int m,n,sum = 0;
    cin >> m >> n;

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

    sort(a+1,a+m+1);

    for (int i = 1; i <= n; ++i)
    {
        cin >> b[i];
        int l = 1,r = m,mid;
        while(l < r)
        {
            mid = (l + r) / 2;
            if(a[mid] >= b[i]){r = mid;}
            else{l = mid + 1;}
        }
        if(l == 1 && l == n){sum += b[i]- a[l];}
        else if(l == n){sum += min({abs(b[i]- a[l - 1]),abs(b[i]- a[l])});}
        else if(l == 1){sum += min({abs(b[i]- a[l]),abs(b[i]- a[l + 1])});}
        else{sum += min({abs(b[i]- a[l - 1]),abs(b[i]- a[l]),abs(b[i]- a[l + 1])});}

    }

    cout << sum << endl;
    return 0;

}

by hhy0311 @ 2023-10-05 21:00:00

第一个,数组不需要开那么大,开1e5即可

第二个,其实b数组没啥用,直接拿一个普通变量即可

主要问题出在最后的累加,不需要这么多特判,只需要判断 L-1 是否为0即可。

完整代码(求个关注,谢谢)

//
// Created by COLORFUL on 2023/9/30.
//
#include "bits/stdc++.h"
#define int long long

using namespace std;
int a[100020000] = {0};

signed main()
{
    int m,n,b,sum = 0;
    cin >> m >> n;

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

    sort(a+1,a+m+1);

    for (int i = 1; i <= n; ++i)
    {
        cin >> b;
        int l = 1,r = m,mid;
        while(l < r)
        {
            mid = (l + r) / 2;
            if(a[mid] >= b){r = mid;}
            else{l = mid + 1;}
        }
        if(l-1==0)
            sum += abs(b- a[l]);
        else
            sum+=min(abs(b- a[l - 1]),abs(b- a[l]));
    }

    cout << sum << endl;
    return 0;

}

by Mrlaolu @ 2023-10-19 11:08:20

@hhy0311 谢谢啦


|