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?