Graphs
113 / 170GraphsLesson 6 of 8About 108 min
A structure that answers are these two joined, and merges groups, both in nearly constant time.
Build the structure, then read it twice. find returns a root, compressing as it goes. union joins two groups and reports whether they were separate. largest_group returns the size of the biggest group once every edge has been applied. edges_until_connected returns how many edges had to be processed before everything became one group, or -1 if that never happens.
Tests
print(largest_group(5, [(0, 1), (1, 2), (3, 4)]), largest_group(3, []), largest_group(0, []))print(edges_until_connected(4, [(0, 1), (2, 3), (1, 2)]), edges_until_connected(4, [(0, 1), (2, 3)]), edges_until_connected(1, []))parent = make(4)print(union(parent, 0, 1), union(parent, 1, 0))print(find(parent, 0) == find(parent, 1))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.