Topic link
Greedy simulated for a long time, and finally gave up
Title
Give you a string from 1 − n 1-n1−A sequence of n , part of which is unknown (represented as 0). The completion sequence makes the number of
adjacent valuesopposite in parity, the least number ofadjacent values, and the opposite: two adjacent values, one of which is odd and the other is even
analysis
Greedy was used at the beginning, but the result was stuck in the twelfth example, and then changed to dp to
define the dp array as follows
int dp[120][60][2];
// dp[i][j][0/1] 表示第i+1个位置放了偶/奇数,且到第i+1处总共放了j个奇数,有多少个奇偶性相反
Get state transition equation
dp[i][j][1] = min(dp[i - 1][j - 1][0] + 1, dp[i - 1][j - 1][1]);
dp[i][j][0] = min(dp[i - 1][j][1] + 1, dp[i - 1][j][0]);
Of course, it depends on whether the position itself already has a value. If it is 0, both are needed. If there is already a value, perform dp according to the original value.
AC code
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
int dp[120][60][2], value[120];
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> value[i];
}
memset(dp, 0x3f, sizeof(dp));
if (value[0] == 0)
dp[0][1][1] = dp[0][0][0] = 0;
else
dp[0][value[0] & 1][value[0] & 1] = 0;
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= min(i + 1, (n + 1) / 2); ++j) {
if ((value[i] & 1 || value[i] == 0) && j > 0)
dp[i][j][1] = min(dp[i - 1][j - 1][0] + 1, dp[i - 1][j - 1][1]);
if (!(value[i] & 1))
dp[i][j][0] = min(dp[i - 1][j][1] + 1, dp[i - 1][j][0]);
}
}
cout << min(dp[n - 1][(n + 1) / 2][1], dp[n - 1][(n + 1) / 2][0]) << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
#ifdef ACM_LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long long test_index_for_debug = 1;
char acm_local_for_debug;
while (cin >> acm_local_for_debug) {
cin.putback(acm_local_for_debug);
if (test_index_for_debug > 20) {
throw runtime_error("Check the stdin!!!");
}
auto start_clock_for_debug = clock();
solve();
auto end_clock_for_debug = clock();
cout << "Test " << test_index_for_debug << " successful" << endl;
cerr << "Test " << test_index_for_debug++ << " Run Time: "
<< double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
cout << "--------------------------------------------------" << endl;
}
#else
solve();
#endif
return 0;
}