C. Garland-----dp+思维/CF

Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.

Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 2). For example, the complexity of 1 4 2 3 5 is 2 and the complexity of 1 3 5 7 6 4 2 is 1.

No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.

Input
The first line contains a single integer n (1≤n≤100) — the number of light bulbs on the garland.

The second line contains n integers p1, p2, …, pn (0≤pi≤n) — the number on the i-th bulb, or 0 if it was removed.

Output
Output a single number — the minimum complexity of the garland.

Examples
inputCopy
5
0 5 0 2 3
outputCopy
2
inputCopy
7
1 0 0 5 0 0 2
outputCopy
1
Note
In the first example, one should place light bulbs as 1 5 4 2 3. In that case, the complexity would be equal to 2, because only (5,4) and (2,3) are the pairs of adjacent bulbs that have different parity.

In the second case, one of the correct answers is 1 7 3 5 6 4 2.

题意:给你1-n个数的排列,有些位置上的数为0,就是让你填没有填进去的数。构成有不同奇偶校验的相邻灯泡对使其最小。

思路:dp
一维:长度
二维:偶数的个数
三维:奇偶性
初始化的条件:
1:长度为1,第一个数为0或者第一个数为偶数。那么 f[1][n/2-1][0]=0;
2:长度为1,第一个数位0或者第一个数位奇数。那么 f[1][n/2][1]=0;
递推方程:
1:当前位置填偶数:f[i][j-1][0]=min(f[i][j-1][0],f[i-1][j][k]+(k==1));
2:当前位置填奇数:f[i][j][1]=min(f[i][j][1],f[i-1][j][k]+(k==0));
结果:
min(f[n][0][0],f[n][0][1]);

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=110;
int f[N][N][2];
int n;
int a[N];
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	memset(f,0x3f,sizeof f);
	//若放的是偶数 
	if(n>1&&(a[1]%2==0||a[1]==0)) f[1][n/2-1][0]=0;
	//若放的是奇数 
	if((a[1]%2==1||a[1]==0) ) f[1][n/2][1]=0;
	for(int i=2;i<=n;i++)
	{
		for(int j=0;j<=n/2;j++)
		{
			for(int k=0;k<2;k++)
			{
				if(j>0&&(a[i]%2==0||a[i]==0))
					f[i][j-1][0]=min(f[i][j-1][0],f[i-1][j][k]+(k==1));
				if((i+j-1<n)&&(a[i]%2==1||a[i]==0)) 
					f[i][j][1]=min(f[i][j][1],f[i-1][j][k]+(k==0));
			}
		}
	 } 
	 cout<<min(f[n][0][0],f[n][0][1])<<endl;
	 return 0;
}

发布了284 篇原创文章 · 获赞 6 · 访问量 3793

猜你喜欢

转载自blog.csdn.net/qq_43690454/article/details/103988771