20分求助!

P1678 烦恼的高考志愿

gghack_Nythix @ 2022-12-12 11:53:46

题解里提到了lower_bound我就用的这个20分!

#include <bits/stdc++.h>
using namespace std;
int a[11451419],b[11451419];
int main()
{
    int m,n,ans = 0;
    cin >> m >> n;
    for(int i = 1;i <= m;i ++)
    {
        cin >> a[i];
    }
    sort(a + 1,a + n + 1);
    for(int i = 1;i <= n;i ++)
    {
        cin >> b[i];
        int temp = lower_bound(a + 1,a + n + 1,b[i]) - a;
        if(temp == m + 1)
        {
            ans += b[i] - a[m];
        }
        else if(temp == 1)
        {
            ans += a[1] - b[i];
        }
        else
        {
            ans += min(abs(a[temp] - b[i]),abs(b[i] - a[temp - 1]));
        }   
    }
    cout << ans;
    return 0;
}

by 137QWQ @ 2022-12-12 12:24:35

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


by Jettblue @ 2022-12-12 12:33:46

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


by The_Wandering_Earth @ 2022-12-14 15:23:30

@gghack_m3d,好像不是光排序有问题,我改了之后也只有10分,应该得等他输入完之后再把b排序一遍吧。要不然特判就行不通,你无法确保最小的在第一个,最大的在最后。


by The_Wandering_Earth @ 2022-12-14 15:35:41

还有lower_bound那里也要改成m

#include <bits/stdc++.h>
using namespace std;
int a[11451419],b[11451419];
long long ans;
int main()
{
    int m,n;
    cin >> m >> n;
    for(int i = 1;i <= m;i ++)
    {
        cin >> a[i];
    }
    for(int i = 1;i <= n;i ++)
    {
        cin >> b[i];
    }
    sort(a + 1,a + m + 1);
    sort(b + 1,b + n + 1);
    for(int i = 1;i <= n;i ++)
    {
        int temp = lower_bound(a + 1,a + m + 1,b[i]) - a;
        if(temp == m + 1)
        {
            ans += b[i] - a[m];
        }
        else if(temp == 1)
        {
            ans += a[1] - b[i];
        }
        else
        {
            ans += min(abs(a[temp] - b[i]),abs(a[temp - 1] - b[i]));
        }   
    }
    cout << ans;
    return 0;
}

by gghack_Nythix @ 2022-12-14 16:47:14

@Jettblue 谢谢AC了


by gghack_Nythix @ 2022-12-14 16:47:29

@137QWQ 谢谢


by gghack_Nythix @ 2022-12-14 16:47:56

@zhangpeinan123 谢谢大佬ac了


|