二分查找,只有60分,#2,#3,#9,#10没过,请求高手支援

P1678 烦恼的高考志愿

weiming3 @ 2023-04-03 20:01:42


#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
int m, n;
vector<int> school;
vector<int> student;
vector<int> my_index;
int check(int school_index, int student_index);
int binary_search(int x);
int main() {
    cin >> m >> n;
    for (int i = 1; i <= m; i++) {
        int x;
        cin >> x;
        school.push_back(x);
    }
    for (int i = 1; i <= n; i++) {
        int x;
        cin >> x;
        student.push_back(x);
    }
    sort(school.begin(), school.end());
    sort(student.begin(), student.end());
    for (int i = 0; i <= n - 1; i++) {
        my_index.push_back(binary_search(i));
    }
    long long int ans = 0;
    for (int i = 0; i <= n - 1; i++) {
        if (i - 1 < 0) {
            ans += school[my_index[i]] - student[i];
        } else {
            ans += min(school[my_index[i]] - student[i],
                       student[i] - school[my_index[i]-1]);
        }
    }
    cout << ans;
    return 0;
}
int binary_search(int x) {
    int ans = 0;
    int left = 0;
    int right = m - 1;
    while (left <= right) {
        int mid = (left + right) >> 1;
        if (check(mid, x)) {
            ans = mid;
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return ans;
}
int check(int school_index, int student_index) {
    if (student[student_index] <= school[school_index]) {
        return 1;
    } else {
        return 0;
    }
}

by uberking @ 2023-05-02 10:48:05

@weiming3 AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=100010;
int sch[N],stu[N];
LL ans;
int n,m;

//找到第一个学校录取分数大于等于自己的分数 
void solve(int i){
    int l=1,r=n;
    while(l<r){
        int mid=l+r>>1;
        if( sch[mid]>=stu[i] )  r=mid;
        else l=mid+1;   
    }
    //最小值在 r 或者 r-1 
    ans+=LL(min(sch[r]-stu[i],stu[i]-sch[r-1]));
    return ; 
}

int main(){
    scanf("%d%d",&n,&m);

    for(int i=1;i<=n;i++)   cin>>sch[i];
    for(int i=1;i<=m;i++)   cin>>stu[i];

    sort(sch+1,sch+n+1);
    sort(stu+1,stu+m+1);

    for(int i=1;i<=m;i++){
        //  1、自己分数是最高的 (随便上)        没学校录取分超过自己 
        //  2、自己分数是最低的 (没学上)        没学校录取分低于自己
        //  2、自己分数夹在中间  (有学上)       有学校录取 
        if(stu[i]>=sch[n])  ans+=LL(stu[i]-sch[n]);
        else if(stu[i]<sch[1])  ans+=LL(sch[1]-stu[i]);
        else solve(i);
    }
    printf("%lld\n",ans);
    return 0;
}

|