https://codeforces.com/contest/1525/problem/D
思路:
两个人的移动轨迹如果交叉了不会变优。
若两个人在位置x,y,x移动到p,y移动到q,
不妨设:
若q<x<y<p,则y-q+p-x不如x-q+p-y;
若x<q≤p<y,则p-x+y-q不如q-x+y-p。
若x<y<p<q,则p-y+q-x=p-x+q-y
因此对于最后一个人转移,将其定于上一个位置之后的任意一个空位置可以获得不会更差的状态。由此转移。
dp[i][j]:前i个人放到前j个空位置的最小代价。
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e3+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL a[maxn],b[maxn],c[maxn];
LL dp[maxn][maxn];
LL tot1=0;LL tot2=0;
int main(void){
cin.tie(0);std::ios::sync_with_stdio(false);
LL n;cin>>n;
for(LL i=1;i<=n;i++){
cin>>a[i];
if(a[i]) b[++tot1]=i;///人
else c[++tot2]=i;///空位置
}
memset(dp,0x3f,sizeof(dp));
for(LL j=0;j<=tot2;j++){
dp[0][j]=0;
}
for(LL i=1;i<=tot1;i++){
for(LL j=i;j<=tot2;j++){
dp[i][j]=min(dp[i][j-1],dp[i-1][j-1]+abs(b[i]-c[j]));
}
}
cout<<dp[tot1][tot2]<<"\n";
return 0;
}