#1#3#8#10wa了

P1678 烦恼的高考志愿

sub15 @ 2023-09-04 13:12:17


#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXM = 1e5 + 10;
ll fs[MAXM] , ls[MAXM];
int main(){
    //freopen("P1678_1.in","r",stdin);
    //freopen("P1.out","w",stdout);
    ll n,m;
    ll ans = 0;
    cin >> n >> m;
    for(int i = 1; i <= n;i++){
        scanf("%d",&fs[i]);
    }
    for(int i = 1;i <= m;i++){
        scanf("%d",&ls[i]);
    }
    sort(fs + 1,fs + n + 1);
    sort(ls + 1,ls + m + 1);
    for(int i = 1;i <= m;i++){
        if(ls[i] > fs[n]){
            ans += ls[i] - fs[n];
        }
        else{
            ans += min(abs(fs[lower_bound(fs + 1,fs + n + 1,ls[i]) - fs ] - ls[i]), abs(fs[lower_bound(fs + 1,fs + n + 1,ls[i]) - fs - 1] - ls[i]));
        }
    }
    cout << ans ;
    return 0;
}

by feather02 @ 2023-09-04 14:43:48

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXM = 1e5 + 10;
ll fs[MAXM] , ls[MAXM];
int main(){
    //freopen("P1678_1.in","r",stdin);
    //freopen("P1.out","w",stdout);
    ll n,m;
    ll ans = 0;
    cin >> n >> m;
    for(int i = 1; i <= n;i++){
        scanf("%lld",&fs[i]);
    }
    for(int i = 1;i <= m;i++){
        scanf("%lld",&ls[i]);
    }
    sort(fs + 1,fs + n + 1);
    for(int i = 1;i <= m;i++){
        if(ls[i] <= fs[1]){
            ans += fs[1] - ls[i];
        }
        else{
            ll x = lower_bound(fs + 1, fs + n + 1, ls[i]) - fs;
            ans += min(abs(fs[x] - ls[i]), abs(fs[x - 1] - ls[i]));
        }
    }
    cout << ans ;
    return 0;
}
  1. 如果用 lower_bound 没必要对学生排序
  2. 如果你把大于 fs[n] 的 ls[i] 返回了,那么就应该手写一个找小于等于当前 ls[i] 的二分,不然的话就会出问题,例如下面这个例子
1 1
100
1

正确答案显然是 99 , 但是你的程序会输出 1


by feather02 @ 2023-09-04 14:45:19

@sub15


by sub15 @ 2023-09-05 22:54:45

@feather02 谢谢大佬,%%%


|