40分求助!..4,5,7,9过了其他wa..救救孩子8

P1678 烦恼的高考志愿

wff13 @ 2021-12-07 14:25:32

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

const int N1=1000010;
const int N2=1000010;

int grade[N1],sch[N2];
int m,n;

bool check(int mid,int i)
{
 return  (grade[i]-sch[mid])>=0;
}
int main()
{
    int tol=0;
    cin>>m>>n;
    for(int i=1;i<=m;i++)scanf("%d",&sch[i]);
    for(int i=1;i<=n;i++)scanf("%d",&grade[i]);  
    sort(sch,sch+m);
    for(int i=1;i<=n;i++)
  {
    int l=0,r=m,sum=0;

    while(l<r)
    {
        int mid=l+r+1>>1;
        if(check(mid,i))l=mid;
        else r=mid-1;

    }
    sum=min(abs(grade[i]-sch[l]),abs(grade[i]-sch[l+1]));
    tol+=sum;

  }
    cout<<tol;
}

by StarLbright40 @ 2021-12-07 15:05:46

边界乱七八糟的……


by wff13 @ 2021-12-08 10:17:02

@星光0000 大佬要怎么改..我实在不太明白


by StarLbright40 @ 2021-12-08 21:19:05

@wff13 你的分数线是存在 sch[1]sch[m] 中的, sort 的区间是左闭右开,所以应该写成

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

同样道理,二分的初始区间也应该是 1~n ,也就是

int l=0,r=m,sum=0;

by wff13 @ 2021-12-09 22:36:24

@星光0000 谢谢大佬,感激不尽


|