dive2.D - Armchairs

能让我凌晨一点多爬起来写一篇题解,大概只能去感谢舍友的呼噜声了叭~


D. Armchairs
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n2.

For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i−j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.

You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?

Input
The first line contains one integer n (2≤n≤5000) — the number of armchairs.

The second line contains n integers a1,a2,…,an (0≤ai≤1). ai=1 means that the i-th armchair is initially occupied, ai=0 means that it is initially free. The number of occupied armchairs is at most n2.

Output
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.

解:dive2.D - Armchairs_第1张图片
DP学狗身上了。
这种初始化的方式真的非常巧妙!!!
一下就将上一个人所占的椅子利用极大值,排除在外。
(懒得多写了,困死,直接给代码了)

#include
using namespace std;
const int N=5005;
int a[N],b[N],c1,c2,f[N][N];  //全觉变量未赋值则自动为0
int main()
{
     
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
     
		int x;
		cin>>x;
		if(x==1)
		      a[++c1]=i;
		else 
		      b[++c2]=i;
	}
	memset(f,0x3f,sizeof f);
	for(int i=0;i<=c2;i++)f[0][i]=0;
	for(int i=1;i<=c1;i++)          //对于每一个1进行枚举
		for(int j=1;j<=c2;j++)
		{
     
			f[i][j]=f[i-1][j-1]+abs(a[i]-b[j]);
			f[i][j]=min(f[i][j],f[i][j-1]);  
			//更新每种椅子累加上一个人所用时间的最小值
		}
	cout<<f[c1][c2];
	return 0;
}

你可能感兴趣的:(题解,算法)