c语言TLE求助

P1678 烦恼的高考志愿

Fabonacci @ 2024-03-17 21:13:00

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int cmp(const void* a,const void* b){
    return *(int*)a-*(int*)b;
}
int min(int a,int b){
    if(a>b) return b;
    else return a;
}
int main(){
    int m,n;
    scanf("%d%d",&m,&n);
    int a[m],b[n];
    for(int i=0;i<m;i++){
        scanf("%d",&a[i]);
    }
    for(int i=0;i<n;i++){
        scanf("%d",&b[i]);
    }
    qsort(b,n,sizeof(int),cmp);
    qsort(a,m,sizeof(int),cmp);

    int sum=0;
    for(int i=0;i<n;i++){
        int left=0,right=m-1,mid=(left+right)/2;
        while(1){

        if(a[left]-b[i]>=0) {
            sum+=abs(a[left]-b[i]);
            break;
        }
        else if(a[right]-b[i]<=0) {
            sum+=abs(a[right]-b[i]);
            break;  
        }
        else if(a[mid]-b[i]>0) right=mid;
        else if(a[mid]-b[i]<0) left=mid;
        if(left+1==right) {
            sum+=min(abs(a[left]-b[i]),abs(a[right]-b[i])); 
                break;
            }
        mid=(left+right)/2;
        }
    }
    printf("%d",sum);
    return 0; 
}

|