https://www.luogu.org/problem/P2507
analysis:
This question will not be the first to see what advanced algorithms, certainly greedy ah ah dp
First consider the ai may be equal to BI , directly to sort
But ai! = Bi's , how do?
Read the title! ! !
God gave you shut a door will give you open a window de
arrays a and b are unequal elements within the array
- So it is necessary to exchange
- At this time, the smaller the exchange range, the absolute value and the smaller
Our greedy to think, because each number at most in a, b each in appears once ,
So when a particular ai = bi , then ai! = B (i-1 ), ai! = B (i + 1)
Because it is an absolute value, you do not know ai-b (i-1) and b (i + 1) -ai who more
So to take a minimum
- a1-b1
- a1-b2, a2-b1 (twenty-two exchange)
- a1-b2, a2-b3, (exchange between three) a3-b1
- a1-b3, a2-b1, (exchange between three) a3-b2
Then you will want to ask
So as not to repeat it?
Consider it a (i-1), ai , a (i + 1) becomes AI, A (I +. 1), A (I + 2) , so they push past the linear DP , is not repeated
If you're still not sure about it, see the code will understand
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N=100005;
const long long M=1e13;
int a[N],b[N],n;
long long f[N],ans;
long long Min(long long a,long long b)
{
if (a<b) return a;
return b;
}
long long js(int l,int r)
{
if (a[l]==b[r]) return M;
return abs(a[l]-b[r]);
}
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);
if (n==1&&a[1]==b[1]) printf("-1\n");
else
{
f[0]=0;
for (int i=1; i<=n; i++)
{
ans=M;
if (i>=1) ans=Min(ans,f[i-1]+js(i,i));
if (i>=2) ans=Min(ans,f[i-2]+js(i-1,i)+js(i,i-1));
if (i>=3)
{
ans=Min(ans,f[i-3]+js(i-2,i-1)+js(i-1,i)+js(i,i-2));
ans=Min(ans,f[i-3]+js(i-2,i)+js(i-1,i-2)+js(i,i-1));
}
f[i]=ans;
}
printf("%lld\n",f[n]);
}
return 0;
}