题解:
dp
显然置换不会超过3个
代码:
#include<bits/stdc++.h> using namespace std; const int N=100005; typedef long long ll; int n,a[N],b[N]; ll inf,f[N]; int Abs(int x){return (x>0)?x:-x;} ll calc(int x,int y) { if (x==y) return inf; return (ll)Abs(x-y); } int main() { scanf("%d",&n); for (int i=1;i<=n;i++)scanf("%d%d",&a[i],&b[i]); sort(a+1,a+n+1);sort(b+1,b+n+1); memset(f,127,sizeof(f)); inf=f[0];f[0]=0; for (int i=1;i<=n;++i) { ll x,y,z; if (f[i-1]!=inf) { x=calc(a[i],b[i]); if (x!=inf) f[i]=min(f[i],f[i-1]+x); } if (i>=2) { x=calc(a[i],b[i-1]),y=calc(a[i-1],b[i]); if (x!=inf&&y!=inf) f[i]=min(f[i],f[i-2]+x+y); } if (i>=3) { x=calc(a[i-2],b[i]),y=calc(a[i-1],b[i-1]),z=calc(a[i],b[i-2]); if (x!=inf&&y!=inf&&z!=inf) f[i]=min(f[i],f[i-3]+x+y+z); x=calc(a[i-2],b[i-1]),y=calc(a[i-1],b[i]),z=calc(a[i],b[i-2]); if (x!=inf&&y!=inf&&z!=inf) f[i]=min(f[i],f[i-3]+x+y+z); x=calc(a[i-2],b[i]),y=calc(a[i-1],b[i-2]),z=calc(a[i],b[i-1]); if (x!=inf&&y!=inf&&z!=inf) f[i]=min(f[i],f[i-3]+x+y+z); } } printf("%lld ",f[n]); }