找一找规律就可以发现,只会存在2个交叉或者3个交叉的情况,更多的交叉情况会在之前就被处理掉。
DP一下就行了。
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
template<class T>inline void read(T &res){
static char ch;T flag=1;
while((ch=getchar())<'0'||ch>'9')if(ch=='-')flag=-1;res=ch-48;
while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-48;res*=flag;
}
const int N = 100005,INF = 0x3f3f3f3f;
long long a[N],b[N],n,dp[N];
inline long long Abs(long long a){return a<0?-a:a;}
inline long long V(long long x,long long y){return (x-y)==0?INF:Abs(x-y);}
int main(){
read(n);
for(register int i=1;i<=n;i++)read(a[i]),read(b[i]);
if(n==1&&a[1]==b[1])return printf("-1"),0;
sort(a+1,a+1+n),sort(b+1,b+1+n);
dp[1]=V(a[1],b[1]),dp[2]=min(dp[1]+V(a[2],b[2]),V(a[1],b[2])+V(a[2],b[1]));
for(register int i=3;i<=n;i++){
dp[i]=min(dp[i-1]+V(a[i],b[i]),dp[i-2]+V(a[i-1],b[i])+V(a[i],b[i-1]));
dp[i]=min(dp[i],dp[i-3]+V(a[i],b[i-1])+V(a[i-1],b[i-2])+V(a[i-2],b[i]));
dp[i]=min(dp[i],dp[i-3]+V(a[i-1],b[i])+V(a[i-2],b[i-1])+V(a[i],b[i-2]));
}
cout<<dp[n]<<endl;
return 0;
}