MLE求助

P1678 烦恼的高考志愿

石哈哈 @ 2021-09-18 10:35:22

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int length = 100001;
int sch[length],stu,sum,Sum;
void search(int l,int r,int k)
{
    int mid = (l+r)/2;
    if (r-l==1)
    {
        sum = min(abs(sch[l] - k),abs(sch[r] - k));
        return ;
    }
    if (sch[mid]>=k) search(l,mid,k);
    if (sch[mid]<k) search(mid+1,r,k);
}
int main()
{
    int m,n;
    scanf("%d %d",&m,&n);
    for(int i=0;i<m;i++)scanf("%d",&sch[i]);
    sort(sch,sch+m);
//    for(int i=0;i<m;i++)printf("%d ",sch[i]);printf("\n");
    for(int i=0;i<n;i++)
    {
        scanf("%d",&stu);
        search(0,m-1,stu);
        //printf("%d\n",sum);
        Sum += sum;
    }
    printf("%d",Sum);
    return 0;
}

by Surge_of_Force @ 2021-09-18 11:22:56

盲猜爆栈


by ExplodingKonjac @ 2021-09-18 11:24:26

应该是搜索边界条件写错了

比如 l=1,r=3,mid=2,递归下去就是 l=3,r=3,不满足边界条件,于是就死递归了。

建议用 l=r 作为边界条件


|