本文主要是介绍Codeforces Round #612 (Div. 1) A. Garland(dp动态规划),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:https://codeforc.es/contest/1286/problem/A
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
input
5
0 5 0 2 3
output
2
input
7
1 0 0 5 0 0 2
output
1
题意
有 1 ~ n 的数,将剩余的数填到 pi 为 0 的位置上,使得相邻数奇偶不同的对数最少。
分析
设 f[i][j][k][x] 表示到 i 位置,前面共填了 j 个奇数, k 个偶数进去,当前位置为 x 数( x 为 0 表示偶数,为 1 表示奇数)。
初始化所有 f 都设为极大值。
状态转移方程有:
- 如果第一个数为 0 ,则 f[1][0][1][0] = f[1][1][0][1] = 0 ;如果已经是奇数或偶数,则 f[1][0][0][a[1] % 2] = 0
- 从 2 号位置开始遍历,如果 q[i] 为 0 ,则我们可以在这个位置放上奇数或偶数,遍历填入奇数偶数的个数所有情况,如果该位置放上奇数:f[i][j][k][1] = min(f[i - 1][j - 1][k][0] + 1, f[i - 1][j - 1][k][1]) ;如果放上偶数: f[i][j][k][0] = min(f[i - 1][j][k - 1][0], f[i - 1][j][k - 1][1] + 1)
- 如果 q[i] 为奇数或偶数,遍历填入奇数偶数的个数所有情况,f[i][j][k][q] = min(f[i - 1][j][k][q], f[i - 1][j][k][q ^ 1] + 1)
代码
#include<bits/stdc++.h>
using namespace std;int n;
int a[107],ji,ou,vis[107];
int f[107][107][107][2];int main()
{cin>>n;for(int i=1;i<=n;i++){scanf("%d",&a[i]);vis[a[i]] = 1;}for(int i=1;i<=n;i++)if(vis[i] == 0) i % 2 == 0 ? ou++ : ji++;memset(f, 0x3f3f3f3f, sizeof(f));int sum = 0;if(a[1] == 0) sum++, f[1][0][1][0] = f[1][1][0][1] = 0;else f[1][0][0][a[1] % 2] = 0;for(int i=2;i<=n;i++){if(a[i] == 0){sum++;for(int j=0;j<=min(sum, ji);j++){int k = sum - j;if(k > ou) continue;if(j >= 1)f[i][j][k][1] = min(f[i - 1][j - 1][k][0] + 1, f[i - 1][j - 1][k][1]);if(k >= 1)f[i][j][k][0] = min(f[i - 1][j][k - 1][0], f[i - 1][j][k - 1][1] + 1);}}else{int q = a[i] % 2;for(int j=0;j<=min(sum, ji);j++){int k = sum - j;if(k > ou) continue;f[i][j][k][q] = min(f[i - 1][j][k][q], f[i - 1][j][k][q ^ 1] + 1);}}}cout<<min(f[n][ji][ou][0],f[n][ji][ou][1]);return 0;
}
这篇关于Codeforces Round #612 (Div. 1) A. Garland(dp动态规划)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!