Editorial for Wesley's Anger Contest 1 Problem 4 (Easy Version) - A Red-Black Tree Problem


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: wleung_bvg

Subtask 1

We can go through all 2N subsets of vertices using a bitmask technique and count the number of subsets that have exactly K vertices, and at least 2 red and 2 black vertices, and forms a single connected component, using breadth first search, depth first search, of the union find data structure.

Time Complexity: O(N2N)

Subtask 2

For the second subtask, we can go through all triples of edges and check if the edges form a single connected component. If it does, then there must be exactly 4 vertices in the connected component. From here, we can check that there are 2 red and 2 black vertices.

Time Complexity: O(N3)

Subtask 3

For the third subtask, we will do dynamic programming on a tree. First, we will arbitrarily root the tree at a vertex. For each vertex, we will have dp[v][i][r][b] be the number of subgraphs that are in the subtree of vertex v, that include vertex v, with size i, r red vertices, and b black vertices. A quick time and memory optimization is that we only need to keep track of r,b2. For each vertex, we can go through each of its children and merge the dp arrays. Let w be a child of v. To merge the arrays dp[v] and dp[w], for all tuples (i,ri,bi,j,rj,bj), we will add the product of dp[v][i][ri][bi] and dp[w][j][rj][bj] to merged[i+j][min(2,ri+rj)][min(2,bi+bj)]. Remember to mod correctly. The final answer will be the sum of dp[v][K][2][2] for all vertices v (1vN).

Time Complexity: O(NK2)


Comments

There are no comments at the moment.