ZOJ4043 : Virtual Singers

将全部$A$和$B$混在一块儿排序,那么每一个$B$要匹配一个$A$,从左往右依次考虑每一个数:spa

若是是一个$B$:blog

  • 若是左边没有多余的$A$,那么将其放入堆$q_C$中,表示这个$B$还未匹配。
  • 不然选择左边代价最小的$A$和这个$B$进行匹配,并把代价取反,加上这个$B$往右匹配的贡献后放入堆$q_B$中,表示将来某个$A$抢走这个$B$的代价,即费用流的反悔操做。

若是是一个$A$:排序

  • 若是$q_C$非空,那么将该$A$直接与$q_C$中代价最小的$B$进行匹配便可。
  • 不然若是$q_B$非空且抢走以前的某个$B$更优,那么抢走以前的$B$,并把这个代价取反,加上这个$A$往右匹配的贡献后放入堆$q_A$中,同理表示费用流的反悔操做。
  • 不然说明这个$A$暂时不须要和左边某个$B$进行匹配,将其放入待命区,也就是堆$q_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);
  }
}
相关文章
相关标签/搜索