悬关 虽然过了但还是不懂lr的设置

P1678 烦恼的高考志愿

Noldo @ 2024-03-28 16:39:26

#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int n, m;
int stuscore[N];
int schscore[N];
long long l, r;
long long ans = 0;
int cal(int i) {
    int x = abs(stuscore[i] - schscore[l]);
    int y = abs(stuscore[i] - schscore[r]);
    if (l == -1)return y;
    if (x > y)return y;
    else return x;
}
int main(){
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        cin >> schscore[i];
    }
    for (int i = 0; i < m; i++) {
        cin >> stuscore[i];
    }
    sort(schscore,schscore+n);
    for (int i = 0; i < m; i++) {
        l = 0, r = n-1;
        while (l +1< r) {
                int mid = (l + r) / 2;
                if (stuscore[i] < schscore[mid])r = mid;
                else l = mid;
            }
        ans += cal(i);
    }
    cout << ans << endl;
    return 0;
}

by Noldo @ 2024-03-28 16:41:05

对于上述代码,我将l r分别设置为-1 n+1只有60分而设置为0 n却全AC了,不理解呀???


by Tazige @ 2024-03-28 22:43:17

@Noldo 我也是不懂


by Liuxb @ 2024-04-05 10:45:57

@Noldo 数组下标是0~n-1,l,r是下标取-1越界了


by Noldo @ 2024-04-05 16:38:19

@Liuxb 不太可能吧,我在cal函数里已经对l=-1的情况进行处理了,而mid=(l+r)/2也算不出来-1呀


by Liuxb @ 2024-04-06 00:09:52

@Liuxb 眼瞎抱歉


by Liuxb @ 2024-04-06 00:13:44

@Liuxb 有越界l取n,r取到了n+1,设置r=n可以过的


|