DMOJ · coci22c4p2

Zrinka

This C++ solution uses dynamic programming for DMOJ coci22c4p2 Zrinka. Read the reasoning, inspect the code, or try your own test case below.

coci22c4p2Dynamic programmingC++32 lines
Solution241of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Dynamic programming

Zrinka matches two binary arrays and minimizing the largest distinct parity-constrained increasing replacement value.

Dynamic programming

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

2_Zrinka.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    using ll = long long;
    using i128 = __int128;
    const int inf = 1e9;
    const ll INF = 1e18; //❄️
    int main() {
        ios::sync_with_stdio(0); cin.tie(0); 
        int n; cin >> n;
        vector<int> v(n);
        for (int i = 0; i < n; i++) cin >> v[i];
        int m; cin >> m;
        vector<int> a(m);
        for (int i = 0; i < m; i++) cin >> a[i];
        vector<vector<array<int, 2>>> dp(n + 1, vector<array<int, 2>>(m + 1, {inf, inf}));
        auto calc = [&] (int cur, int p) {
            return ((cur + 1 & 1) == p ? cur + 1 : cur + 2);
        };
        dp[0][0][0] = dp[0][0][1] = 0;
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                if (i > 0) {
                    dp[i][j][0] = min(calc(dp[i - 1][j][0], v[i - 1]), calc(dp[i - 1][j][1], v[i - 1]));
                }
                if (j > 0) {
                    dp[i][j][1] = min(calc(dp[i][j - 1][0], a[j - 1]), calc(dp[i][j - 1][1], a[j - 1]));
                }
            }
        }
        cout << min(dp[n][m][0], dp[n][m][1]) << '\n';
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.