假如不存在相等的两个数不能配对,那很容易贪心得到,A中rank 1匹配B中rank 1
A中rank2 匹配B中rank 2……
有了相等不能匹配这个条件,那么A中rank i可能和rank i,i-1,i+1匹配
也有可能三对数字交换匹配
dp一下就好了
1 const inf=2000010; 2 type node=array[0..100010] of longint; 3 var a,b:node; 4 f:array[0..100010] of int64; 5 n,i:longint; 6 7 function min(a,b:int64):int64; 8 begin 9 if a>b then exit(b) else exit(a); 10 end; 11 12 function calc(a,b:longint):longint; 13 begin 14 if a=b then exit(inf) 15 else exit(abs(a-b)); 16 end; 17 18 procedure qsort(var a:node); 19 procedure sort(l,r:longint); 20 var i,j,x,y: longint; 21 begin 22 i:=l; 23 j:=r; 24 x:=a[(l+r) div 2]; 25 repeat 26 while a[i]<x do inc(i); 27 while x<a[j] do dec(j); 28 if not(i>j) then 29 begin 30 y:=a[i]; 31 a[i]:=a[j]; 32 a[j]:=y; 33 inc(i); 34 j:=j-1; 35 end; 36 until i>j; 37 if l<j then sort(l,j); 38 if i<r then sort(i,r); 39 end; 40 41 begin 42 sort(1,n); 43 end; 44 45 begin 46 readln(n); 47 for i:=1 to n do 48 readln(a[i],b[i]); 49 qsort(a); 50 qsort(b); 51 f[1]:=calc(a[1],b[1]); 52 f[2]:=min(f[1]+calc(a[2],b[2]),calc(a[1],b[2])+calc(a[2],b[1])); 53 for i:=3 to n do 54 begin 55 f[i]:=f[i-1]+calc(a[i],b[i]); 56 f[i]:=min(f[i],f[i-2]+calc(a[i-1],b[i])+calc(a[i],b[i-1])); 57 f[i]:=min(f[i],f[i-3]+calc(a[i],b[i-2])+calc(a[i-1],b[i])+calc(a[i-2],b[i-1])); 58 f[i]:=min(f[i],f[i-3]+calc(a[i],b[i-1])+calc(a[i-1],b[i-2])+calc(a[i-2],b[i])); 59 end; 60 if f[n]=inf then writeln(-1) else writeln(f[n]); 61 end.