581F - Zublicanes and Mumocrates - CodeForces Solution


dp trees two pointers *2400

Please click on ads to support us..

C++ Code:

/* Oon commento looloo bord */

#include <bits/stdc++.h>

using namespace std;

const int N = 5'000 + 7, INF = 1'000'000'000;

int n, dp[2][N][N], nl[N], tmp[2][N];
vector<int> adj[N];

void read_input() {
    cin >> n;
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v;
        --u, --v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
}

void update(int v, int u) {
    for (int i = 0; i <= nl[v] + nl[u]; i++)
        tmp[0][i] = tmp[1][i] = INF;
    for (int i = 0; i <= nl[v]; i++)
        for (int j = 0; j <= nl[u]; j++)
            for (int colv: {0, 1})
                for (int colu: {0, 1})
                    tmp[colv][i + j] = min(tmp[colv][i + j], dp[colv][v][i] + dp[colu][u][j] + (colv != colu));
    for (int i = 0; i <= nl[v] + nl[u]; i++)
        for (int id: {0, 1})
            dp[id][v][i] = tmp[id][i];
}

void dfs(int v, int par = -1) {
    if ((int) adj[v].size() == 1) {
        nl[v] = 1;
        dp[1][v][1] = dp[0][v][0] = 0;
    }
    else
        dp[1][v][0] = dp[0][v][0] = 0;
    for (int u: adj[v])
        if (u != par) {
            dfs(u, v);
            update(v, u);
            nl[v] += nl[u];
        }
}

int main() {
    memset(dp, 63, sizeof dp);
    read_input();
    dfs(0);
    cout << min(dp[0][0][nl[0] / 2], dp[1][0][nl[0] / 2]) << endl;
}


Comments

Submit
0 Comments
More Questions

361A - Levko and Table
5E - Bindian Signalizing
687A - NP-Hard Problem
1542C - Strange Function
961E - Tufurama
129D - String
888A - Local Extrema
722B - Verse Pattern
278A - Circle Line
940A - Points on the line
1742C - Stripes
1742F - Smaller
1742B - Increasing
1742A - Sum
1742D - Coprime
390A - Inna and Alarm Clock
1398B - Substring Removal Game
1742G - Orray
416B - Art Union
962A - Equator
803B - Distances to Zero
291A - Spyke Talks
1742E - Scuza
1506D - Epic Transformation
1354G - Find a Gift
1426F - Number of Subsequences
1146B - Hate "A"
1718C - Tonya and Burenka-179
834A - The Useless Toy
1407D - Discrete Centrifugal Jumps