0

Given a tree with n vertices and q queries (n, q <= 5*10^5), where for each query you either remove or bring back a previously deleted vertex, output the number of connected components after each operation.

I've tried using this formula

components = components + (removing ? 1 : -1)*(degree[v] - 1)

where v is the vertex being removed/recovered.

The issue here is I have to keep track of all degrees and either update degrees of all neighbors of v or mark which nodes are deleted and compute degree of v by checking which of its neighbors are deleted, both solutions require iterating over the adjacency list of v.

I've thought about reversing the query order and/or using disjoint sets but that'd still be treating each edge individually.

Is there a way to improve this solution?

Insomniac
  • 639
  • 3
  • 19
rambo42
  • 1
  • 3

1 Answers1

0

Ok, here's what I came up with:

First, root the tree arbitrarily, while also computing a parent and degree array. I also made the tree directed, so all degrees were smaller by one except the root's, but that might not be necessary.

Now only the degree of the parent needs to be updated when updating a node.

sign = removing ? 1 : -1
if v == root
  components += sign*(deg[v] - 1)
else
  deg[parent[v]] -= sign
  components += sign*(deg[v] - deleted[parent[v]])

where deleted is a boolean array.

Also found out this holds for a forest

components(E, V) = V - E
rambo42
  • 1
  • 3