[AtCoder ABC302] F - Merge Set

Problem Statement

 

If we add edges between every pair of sets that have shared elements, there will be O(N^2) edges to traverse. 

Instead, we can add N extra virtual vertices from 1 to N, each virtual node contains a single number. 

Then we connect all sets to these N virtual vertices. There will be O(SUM of |SET|) edges, which is bounded by 5 * 10^5. 

To find out the minimum steps to reach from 1 to M, we do a bfs and divide the min distance by 2 as the introduction of virtual nodes makes each 1 step hop to a 2 steps hop.

posted @ 2023-07-17 10:54  Review->Improve  阅读(38)  评论(0编辑  收藏  举报