求问为什么全WA

P1678 烦恼的高考志愿

peaceandlove2002 @ 2021-09-18 17:14:10

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int cmp(const void*a,const void*b){
    return (*(int*)a-*(int *)b);
}

int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    int a[n+5],b[m+5],i;
    for(i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    qsort(a,n,sizeof(int),cmp);
    for(i=0;i<m;i++){
        scanf("%d",&b[i]);
    }
    //qsort(b,m,sizeof(int),cmp);   

    long long s=0;
    int flag=0;
    for(i=0;i<m;i++){
    int left=0,right=n-1;
    while(left<=right){
        int mid=(right-left)/2+left;
        if(b[i]<a[mid]) right=mid-1;
        else if(b[i]>a[mid])left=mid+1;
        else if(b[i]==a[mid]){
         break;flag=1;}
    }
    if(flag==1){
        s=s+0;
    }
    if(flag==0){
    int x2=abs(a[left]-b[i]),min;
    if(left!=0&&left!=n-1){
    int x1=abs(a[left-1]-b[i]);
    int j;
        min=x1;
        for(j=left-1;j<=left+1;j++) 
            if(abs(a[j]-b[i])<min) min=abs(a[j]-b[i]);

    }
    else if(left==0){
    int x3=abs(a[left+1]-b[i]);
    min=x2<=x3?x2:x3;
    }
    else if(left==n-1){

        int x1=abs(a[left-1]-b[i]);
        min=x2<=x1?x2:x1;

    }
        s=s+min;
    }

}
    printf("%lld",s);
}

|