D - Change Usernames Editorial by en_translator
Hint
Some queries have dependencies: “a handle cannot be changed until another user’s one is changed.” Draw a dependency graph to determine priorities.
Solution
Consider a graph whose vertices are the strings and directed edges go from \(S_i\) to \(T_i\). If this graph has a cycle, the corresponding handle changes are impossible, so the answer is No
. Otherwise, one can repeatedly “find an edge going to a vertex with outdegree \(0\), perform the corresponding change, and remove the vertex” to fulfill all the requests, so the answer is Yes
.
Therefore, it is sufficient to detect a cycle in a graph, which can be done with DFS (Depth-First Search), BFS (Breadth-First Search), or the Disjoint Set Union.
posted:
last update: