D. Armchairs(dp+贪心)

58 篇文章 0 订阅

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;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值