求大佬解释

P1678 烦恼的高考志愿

Selvare @ 2020-11-02 21:40:46

蒟蒻自己想用二分写,但是不管怎么改都爆零

然后在某一次改动后,成了下面那样:

#include<iostream>
#include<algorithm>
#include<cmath>
#define maxn 100005
using namespace std;
int a[maxn], sum = 0;
void find(int x, int l, int r)
{   
    int mid = (l+r)/2;
    if(l+1 == r || l == r )
    {
        sum += min(min(abs(x-a[l]), abs(x-a[l+1])), min(abs(x-a[r]), abs(x-a[r-1])));
        return;
    }
    if(a[mid] >= x) find(x, l, mid);
    else find(x, mid+1, r);
}
int main()
{
    int m, n, x;
    cin >> m >> n;
    for(int i = 1; i <= m; i++)
        cin >> a[i];
    sort(a+1, a+1+m);   
    for(int i = 1; i <= n; i++)
    {
        cin >> x;
        if(a[1] > x) sum += abs(a[1] - x);
        else if(x > a[m]) sum += abs(x - a[m]);
        else find(x, 1, m);
    }   
    cout << sum;
    return 0;
} 

但是依旧爆零。。。

于是我尝试着,改了下第15行:

sum += min(min(abs(x-a[l]), abs(x-a[l-1])), min(abs(x-a[r]), abs(x-a[r+1])));

然后就过了??? 我不太懂为什么。。。


by Selvare @ 2020-11-02 21:41:55

诶呀貌似是第12行那个


by 旭日临窗 @ 2020-11-02 21:50:40

@Selvare

建议用循环写二分


by Selvare @ 2020-11-02 22:03:43

@旭日临窗 啊这,为什么啊


|