wa求助

P1678 烦恼的高考志愿

老撕鸡 @ 2021-03-06 08:48:20

#include<bits/stdc++.h>
using namespace std;
long long a[100005],b[100005],m,n,a1=0,ans;
void qsort(long long l,long long r) {
    long long i,j,mid,p;
    i=l;
    j=r;
    mid=a[(l+r)/2];
    while(i<=j) {
        while(a[i]>mid) i++;
        while(a[j]<mid) j--;
        if(i<=j) {
            p=a[i];
            a[i]=a[j];
            a[j]=p;
            i++;
            j--;
        }
    }
    if(l<j) qsort(l,j);
    if(i<r) qsort(i,r);
}
void qsort1(long long l,long long r) {
    long long i,j,mid,p;
    i=l;
    j=r;
    mid=b[(l+r)/2];
    while(i<=j) {
        while(b[i]>mid) i++;
        while(b[j]<mid) j--;
        if(i<=j) {
            p=b[i];
            b[i]=b[j];
            b[j]=p;
            i++;
            j--;
        }
    }
    if(l<j) qsort1(l,j);
    if(i<r) qsort1(i,r);
}
long long abs1(long long aa,long long bb)
{
    if(aa>bb) return aa-bb;
    return bb-aa;
}
int main() {
    cin>>m>>n;
    for(int i=1; i<=m; i++) cin>>a[i];
    for(int i=1; i<=n; i++) cin>>b[i];
    qsort(1,m);
    qsort1(1,n);
    a1=1;
    for(int i=1; i<=n; i++) {
        while(abs1(a[a1],b[i])>abs1(a[a1+1],b[i])&&a1<m) a1++;
        ans+=abs1(a[a1],b[i]);
    }
    cout<<ans;
    return 0;
}

|