將全部$A$和$B$混在一塊兒排序,那麼每一個$B$要匹配一個$A$,從左往右依次考慮每一個數:spa
若是是一個$B$:blog
若是是一個$A$:排序
顯然每一個數只會進行$O(1)$次堆操做,故時間複雜度爲$O((n+m)\log (n+m))$。it
#include<cstdio> #include<queue> #include<vector> #include<algorithm> using namespace std; typedef long long ll; int Case,n,m,i,ce,x;ll ans; struct E{int x,y;E(){}E(int _x,int _y){x=_x,y=_y;}}e[200010]; inline bool cmp(const E&a,const E&b){return a.x<b.x;} int main(){ scanf("%d",&Case); while(Case--){ priority_queue<ll,vector<ll>,greater<ll> >A,B,C; scanf("%d%d",&n,&m); ce=0; while(n--){ scanf("%d",&x); e[++ce]=E(x,0); } while(m--){ scanf("%d",&x); e[++ce]=E(x,1); } sort(e+1,e+ce+1,cmp); ans=0; for(i=1;i<=ce;i++){ ll x=e[i].x; if(e[i].y==0){ if(!C.empty()){ ll t=C.top(); C.pop(); ans+=x+t; }else if(!B.empty()){ ll t=B.top(); if(t+x<0){ B.pop(); ans+=x+t; A.push(-t-x-x); }else A.push(-x); }else A.push(-x); }else{ if(!A.empty()){ ll t=A.top(); A.pop(); ans+=x+t; B.push(-t-x-x); }else C.push(-x); } } printf("%lld\n",ans); } }