From f3e58c0f05cc7107e0a888d5c24617083ffc7671 Mon Sep 17 00:00:00 2001 From: Sagar Pandya Date: Wed, 28 Oct 2020 18:07:01 +0530 Subject: [PATCH] made find_set method efficient --- graph/connected_components_with_dsu.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/graph/connected_components_with_dsu.cpp b/graph/connected_components_with_dsu.cpp index 191c2bc88..c582d6f58 100644 --- a/graph/connected_components_with_dsu.cpp +++ b/graph/connected_components_with_dsu.cpp @@ -7,7 +7,7 @@ * * ### Algorithm * In Graph, if you have to find out the number of connected components, there are 2 options - * 1. Use Depth first search + * 1. Depth first search * 2. Disjoint union * 1st option is inefficient, Disjoint union is the most optimal way to find this. */ @@ -34,10 +34,11 @@ void make_set() { * @return parent of val */ int find_set(int val) { - if (val == parent[val]) { - return val; + while (parent[val] != val) { + parent[val] = parent[parent[val]]; + val = parent[val]; } - return parent[val] = find_set(parent[val]); + return val; } /** * @brief To join 2 components to belong to one