Official

E - Good Graph Editorial by en_translator


Assign a distinct ID (like an integer) to each connected component of graph \(G\). We simply call the connected with component with ID \(c\) “component \(c\).” For each vertex \(w\), let \(\mathrm{id}(w)\) be the ID of the connected component that \(w\) belongs. For example, vertices \(u\) and \(v\) belong to the same connected component if and only if \(\mathrm{id}(u) = \mathrm{id}(v)\).

If an edge connecting vertices \(p\) and \(q\) is added to \(G\), (if \(\mathrm{id}(p) \neq \mathrm{id}(q)\) then) component \(\mathrm{id}(p)\) and component \(\mathrm{id}(q)\) are merged into one.

Thus, we can avoid a path connecting two vertices \(x_i\) and \(y_i\) to exist if and only if an unordered pair \(\lbrace \mathrm{id}(p), \mathrm{id}(q) \rbrace\) and another unordered pair \(\lbrace \mathrm{id}(x_i), \mathrm{id}(y_i) \rbrace\) are different.

Therefore, the graph remains good after adding an edge connecting two vertices \(p\) and \(q\) (that is, no path exists between two vertices \(x_i\) and \(y_i\) for all \(i = 1, 2, \ldots, K\)) if and only if an unordered pair \(\lbrace \mathrm{id}(p), \mathrm{id}(q) \rbrace\) is different from all of the following \(K\) unordered pairs (which may contain duplicates):

\[\lbrace \mathrm{id}(x_1), \mathrm{id}(y_1)\rbrace, \lbrace \mathrm{id}(x_2), \mathrm{id}(y_2)\rbrace, \ldots, \lbrace \mathrm{id}(x_K), \mathrm{id}(y_K)\rbrace. \tag{1} \]

Hence, this problem can be solved by maintaining a set \(S\) of \(K\) unordered pairs listed in (1) as a balanced binary tree beforehand, and for each question \((p_i, q_i)\), determining if \(S\) contains \(\lbrace \mathrm{id}(p_i), \mathrm{id}(q_i) \rbrace\) by accessing that balanced binary tree.

Regarding how to determine and obtain the ID of a connected component, we can manage \(G\) in a DSU (Disjoint Set Union) to obtain, for each vertex \(v\) of \(G\), the representative element of the connected component that \(v\) belongs, using the feature of the DSU; this can be used as the ID \(\mathrm{id}(v)\) of the connected component that \(v\) belongs.

posted:
last update: