program ideone;
var
  AList, BList: TArray<Integer>;
  APairs, BPairs: TArray<TPoint>;
  ia, ib, Res, CntA, CntB: Integer;
  s: string;
begin
  AList := [1,2,2,3,4,5,6,7];
  BList := [1,5,2,3,4,7,5,7];
//  AList := [1,2,2,3];
//  BList := [2,2,2,3];
  SetLength(APairs, Length(AList));
  SetLength(BPairs, Length(BList));

  for ia := 0 to High(AList) do
    if Odd(ia) then
      APairs[ia] := Point(AList[ia], -1)
    else
      APairs[ia] := Point(AList[ia], 1);
  TArray.Sort<TPoint>(APairs, TDelegatedComparer<TPoint>.Construct(
    function(const Left, Right: TPoint): Integer
    begin
      Result := 3 * Left.X - Left.Y - 3 * Right.X + Right.Y;
    end));

  for ib := 0 to High(BList) do
    if Odd(ib) then
      BPairs[ib] := Point(BList[ib], -1)
    else
      BPairs[ib] := Point(BList[ib], 1);
  TArray.Sort<TPoint>(BPairs, TDelegatedComparer<TPoint>.Construct(
    function(const Left, Right: TPoint): Integer
    begin
      Result := 3 * Left.X - Left.Y - 3 * Right.X + Right.Y;
    end));

  CntA := 0;
  CntB := 0;
  Res := 0;
  ia := 0;
  ib := 0;
  while (ia < Length(APairs)) and (ib < Length(BPairs)) do begin
    Writeln(Format('%d:%d (%d)  %d:%d (%d)',
      [APairs[ia].X, APairs[ia].Y, CntA, BPairs[ib].X, BPairs[ib].Y, CntB]));
    if 3 * APairs[ia].X - APairs[ia].Y <= 3 * BPairs[ib].X - BPairs[ib].Y then
    begin
      CntA := CntA + APairs[ia].Y;
      s := 'move A';
      if APairs[ia].Y < 0 then begin
        Res := Res + CntB;
        s := s + Format(' addB %d', [CntB]);
      end;
      Inc(ia);
    end
    else begin
      CntB := CntB + BPairs[ib].Y;
      s := 'move B';
      if BPairs[ib].Y < 0 then begin
        Res := Res + CntA;
        s := s + Format(' addA %d', [CntA]);
      end;
      Inc(ib);
    end;
    Writeln(s);
  end;
  Writeln(Format('Result = %d', [Res]));
end.