The Wayback Machine - https://web.archive.org/web/20240624031856/https://www.geeksforgeeks.org/disjoint-set-union-trees-set-2/
Open In App

Disjoint Set Union on trees | Set 2

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a tree, and the cost of a subtree is defined as |S|*AND(S) where |S| is the size of the subtree and AND(S) is bitwise AND of all indices of nodes from the subtree, task is to find maximum cost of possible subtree.

Prerequisite : Disjoint Set Union

Examples:  

Input : Number of nodes = 4
        Edges = (1, 2), (3, 4), (1, 3)
Output : Maximum cost = 4
Explanation : 
Subtree with singe node {4} gives the maximum cost.

Input : Number of nodes = 6
        Edges = (1, 2), (2, 3), (3, 4), (3, 5), (5, 6)
Output : Maximum cost = 8
Explanation : 
Subtree with nodes {5, 6} gives the maximum cost.

Approach : The strategy is to fix the AND, and find the maximum size of a subtree such that AND of all indices equals to the given AND. Suppose we fix AND as ‘A’. In binary representation of A, if the ith bit is ‘1’, then all indices(nodes) of the required subtree should have ‘1’ in ith position in binary representation. If ith bit is ‘0’ then indices either have ‘0’ or ‘1’ in ith position. That means all elements of subtree are super masks of A. All super masks of A can be generated in O(2^k) time where ‘k’ is the number of bits which are ‘0’ in A. 

Now, the maximum size of subtree with a given AND ‘A’ can be found using DSU on the tree. Let, ‘u’ be the super mask of A and ‘p[u]’ be the parent of u. If p[u] is also a super mask of A, then, we have to update the DSU by merging the components of u and p[u]. Simultaneously, we also have to keep track of the maximum size of subtree. DSU helps us to do it. It will be more clear if we look at following code.

Implementation:

CPP




// CPP code to find maximum possible cost
#include <bits/stdc++.h>
using namespace std;
 
#define N 100010
 
// Edge structure
struct Edge {
    int u, v;
};
 
/* v : Adjacency list representation of Graph
    p : stores parents of nodes */
vector<int> v[N];
int p[N];
 
// Weighted union-find with path compression
struct wunionfind {
    int id[N], sz[N];
    void initial(int n)
    {
        for (int i = 1; i <= n; i++)
            id[i] = i, sz[i] = 1;
    }
 
    int Root(int idx)
    {
        int i = idx;
        while (i != id[i])
            id[i] = id[id[i]], i = id[i];
 
        return i;
    }
 
    void Union(int a, int b)
    {
        int i = Root(a), j = Root(b);
        if (i != j) {
            if (sz[i] >= sz[j]) {
                id[j] = i, sz[i] += sz[j];
                sz[j] = 0;
            }
            else {
                id[i] = j, sz[j] += sz[i];
                sz[i] = 0;
            }
        }
    }
};
 
wunionfind W;
 
// DFS is called to generate parent of
// a node from adjacency list representation
void dfs(int u, int parent)
{
    for (int i = 0; i < v[u].size(); i++) {
        int j = v[u][i];
        if (j != parent) {
            p[j] = u;
            dfs(j, u);
        }
    }
}
 
// Utility function for Union
int UnionUtil(int n)
{
    int ans = 0;
 
    // Fixed 'i' as AND
    for (int i = 1; i <= n; i++) {
        int maxi = 1;
 
        // Generating supermasks of 'i'
        for (int x = i; x <= n; x = (i | (x + 1))) {
            int y = p[x];
 
            // Checking whether p[x] is
            // also a supermask of i.
            if ((y & i) == i) {
                W.Union(x, y);
 
                // Keep track of maximum
                // size of subtree
                maxi = max(maxi, W.sz[W.Root(x)]);
            }
        }
         
        // Storing maximum cost of
        // subtree with a given AND
        ans = max(ans, maxi * i);
         
        // Separating components which are merged
        // during Union operation for next AND value.
        for (int x = i; x <= n; x = (i | (x + 1))) {
            W.sz[x] = 1;
            W.id[x] = x;
        }
    }
         
    return ans;
}
 
// Driver code
int main()
{
    int n, i;
 
    // Number of nodes
    n = 6;
 
    W.initial(n);
 
    Edge e[] = { { 1, 2 }, { 2, 3 }, { 3, 4 },
                 { 3, 5 }, { 5, 6 } };
 
    int q = sizeof(e) / sizeof(e[0]);
 
    // Taking edges as input and put
    // them in adjacency list representation
    for (i = 0; i < q; i++) {
        int x, y;
        x = e[i].u, y = e[i].v;
        v[x].push_back(y);
        v[y].push_back(x);
    }
 
    // Initializing parent vertex of '1' as '1'
    p[1] = 1;
 
    // Call DFS to generate 'p' array
    dfs(1, -1);
 
    int ans = UnionUtil(n);
         
        printf("Maximum Cost = %d\n", ans);
 
    return 0;
}


Java




// Java code to find maximum possible cost
import java.util.*;
 
class GFG
{
 
  // Edge structure
  static class Edge {
    public int u, v;
    public Edge(int u, int v)
    {
      this.u = u;
      this.v = v;
    }
  };
 
  static int N = 100010;
 
  /* v : Adjacency list representation of Graph
        p : stores parents of nodes */
  static ArrayList<ArrayList<Integer> > v
    = new ArrayList<ArrayList<Integer> >();
  static int p[] = new int[N];
 
  // Weighted union-find with path compression
  static class wunionfind {
    int id[] = new int[N];
    int sz[] = new int[N];
    void initial(int n)
    {
      for (int i = 1; i <= n; i++) {
        id[i] = i;
        sz[i] = 1;
      }
    }
 
    int Root(int idx)
    {
      int i = idx;
      while (i != id[i]) {
        id[i] = id[id[i]];
        i = id[i];
      }
 
      return i;
    }
 
    void Union(int a, int b)
    {
      int i = Root(a), j = Root(b);
      if (i != j) {
        if (sz[i] >= sz[j]) {
          id[j] = i;
          sz[i] += sz[j];
          sz[j] = 0;
        }
        else {
          id[i] = j;
          sz[j] += sz[i];
          sz[i] = 0;
        }
      }
    }
  };
 
  static wunionfind W = new wunionfind();
 
  // DFS is called to generate parent of
  // a node from adjacency list representation
  static void dfs(int u, int parent)
  {
    for (int i = 0; i < v.get(u).size(); i++) {
      int j = v.get(u).get(i);
      if (j != parent) {
        p[j] = u;
        dfs(j, u);
      }
    }
  }
 
  // Utility function for Union
  static int UnionUtil(int n)
  {
    int ans = 0;
 
    // Fixed 'i' as AND
    for (int i = 1; i <= n; i++) {
      int maxi = 1;
 
      // Generating supermasks of 'i'
      for (int x = i; x <= n; x = (i | (x + 1))) {
        int y = p[x];
 
        // Checking whether p[x] is
        // also a supermask of i.
        if ((y & i) == i) {
          W.Union(x, y);
 
          // Keep track of maximum
          // size of subtree
          maxi = Math.max(maxi, W.sz[W.Root(x)]);
        }
      }
 
      // Storing maximum cost of
      // subtree with a given AND
      ans = Math.max(ans, maxi * i);
 
      // Separating components which are merged
      // during Union operation for next AND value.
      for (int x = i; x <= n; x = (i | (x + 1))) {
        W.sz[x] = 1;
        W.id[x] = x;
      }
    }
 
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    for (int i = 0; i < N; i++)
      v.add(new ArrayList<Integer>());
 
    int n, i;
 
    // Number of nodes
    n = 6;
 
    W.initial(n);
 
    Edge e[] = { new Edge(1, 2), new Edge(2, 3),
                new Edge(3, 4), new Edge(3, 5),
                new Edge(5, 6) };
 
    int q = e.length;
 
    // Taking edges as input and put
    // them in adjacency list representation
    for (i = 0; i < q; i++) {
      int x, y;
      x = e[i].u;
      y = e[i].v;
      v.get(x).add(y);
      v.get(y).add(x);
    }
 
    // Initializing parent vertex of '1' as '1'
    p[1] = 1;
 
    // Call DFS to generate 'p' array
    dfs(1, -1);
 
    int ans = UnionUtil(n);
 
    System.out.printf("Maximum Cost = %d\n", ans);
  }
}
 
// This code is contributed by phasing17


Python3




# Python3 code to find maximum possible cost
N = 100010
  
# Edge structure
class Edge:
     
    def __init__(self, u, v):
        self.u = u
        self.v = v
  
''' v : Adjacency list representation of Graph
    p : stores parents of nodes '''
 
v=[[] for i in range(N)];
p=[0 for i in range(N)];
  
# Weighted union-find with path compression
class wunionfind:
     
    def __init__(self):
         
        self.id = [0 for i in range(1, N + 1)]
        self.sz = [0 for i in range(1, N + 1)]
     
    def initial(self, n):
         
        for i in range(1, n + 1):
            self.id[i] = i
            self.sz[i] = 1
  
    def Root(self, idx):
     
        i = idx;
         
        while (i != self.id[i]):
            self.id[i] = self.id[self.id[i]]
            i = self.id[i];
  
        return i;
  
    def Union(self, a, b):
     
        i = self.Root(a)
        j = self.Root(b);
         
        if (i != j):
            if (self.sz[i] >= self.sz[j]):
                self.id[j] = i
                self.sz[i] += self.sz[j];
                self.sz[j] = 0;
            else:
                self.id[i] = j
                self.sz[j] += self.sz[i];
                self.sz[i] = 0
  
W = wunionfind()
  
# DFS is called to generate parent of
# a node from adjacency list representation
def dfs(u, parent):
 
    for i in range(0, len(v[u])):
     
        j = v[u][i];
         
        if(j != parent):
            p[j] = u;
            dfs(j, u);
             
# Utility function for Union
def UnionUtil(n):
 
    ans = 0;
  
    # Fixed 'i' as AND
    for i in range(1, n + 1):
     
        maxi = 1;
  
        # Generating supermasks of 'i'
        x = i
        while x<=n:
         
            y = p[x];
  
            # Checking whether p[x] is
            # also a supermask of i.
            if ((y & i) == i):
                W.Union(x, y);
  
                # Keep track of maximum
                # size of subtree
                maxi = max(maxi, W.sz[W.Root(x)]);
             
            x = (i | (x + 1))
            
        # Storing maximum cost of
        # subtree with a given AND
        ans = max(ans, maxi * i);
          
        # Separating components which are merged
        # during Union operation for next AND value.
        x = i
        while x <= n:
            W.sz[x] = 1;
            W.id[x] = x;
            x = (i | (x + 1))
               
    return ans;
  
# Driver code
if __name__=='__main__':
 
    # Number of nodes
    n = 6;
  
    W.initial(n);
  
    e = [ Edge( 1, 2 ), Edge( 2, 3 ), Edge( 3, 4 ),
                 Edge( 3, 5 ), Edge( 5, 6 ) ];
  
    q = len(e)
  
    # Taking edges as input and put
    # them in adjacency list representation
    for i in range(q):
     
        x = e[i].u
        y = e[i].v;
        v[x].append(y);
        v[y].append(x);
      
    # Initializing parent vertex of '1' as '1'
    p[1] = 1;
  
    # Call DFS to generate 'p' array
    dfs(1, -1);
  
    ans = UnionUtil(n);
          
    print("Maximum Cost =", ans)
  
# This code is contributed by rutvik_56   


C#




// C# code to find maximum possible cost
using System;
using System.Collections.Generic;
 
// Edge structure
class Edge {
    public int u, v;
    public Edge(int u, int v)
    {
        this.u = u;
        this.v = v;
    }
};
 
// Weighted union-find with path compression
class wunionfind {
    static int N = 100010;
    public int[] id = new int[N];
    public int[] sz = new int[N];
 
    public void initial(int n)
    {
        for (int i = 1; i <= n; i++) {
            id[i] = i;
            sz[i] = 1;
        }
    }
 
    public int Root(int idx)
    {
        int i = idx;
        while (i != id[i]) {
            id[i] = id[id[i]];
            i = id[i];
        }
 
        return i;
    }
 
    public void Union(int a, int b)
    {
        int i = Root(a), j = Root(b);
        if (i != j) {
            if (sz[i] >= sz[j]) {
                id[j] = i;
                sz[i] += sz[j];
                sz[j] = 0;
            }
            else {
                id[i] = j;
                sz[j] += sz[i];
                sz[i] = 0;
            }
        }
    }
};
 
class GFG {
    static int N = 100010;
 
    /* v : Adjacency list representation of Graph
          p : stores parents of nodes */
    static List<List<int> > v = new List<List<int> >();
    static int[] p = new int[N];
 
    static wunionfind W = new wunionfind();
 
    // DFS is called to generate parent of
    // a node from adjacency list representation
    static void dfs(int u, int parent)
    {
        for (int i = 0; i < v[u].Count; i++) {
            int j = v[u][i];
            if (j != parent) {
                p[j] = u;
                dfs(j, u);
            }
        }
    }
 
    // Utility function for Union
    static int UnionUtil(int n)
    {
        int ans = 0;
 
        // Fixed 'i' as AND
        for (int i = 1; i <= n; i++) {
            int maxi = 1;
 
            // Generating supermasks of 'i'
            for (int x = i; x <= n; x = (i | (x + 1))) {
                int y = p[x];
 
                // Checking whether p[x] is
                // also a supermask of i.
                if ((y & i) == i) {
                    W.Union(x, y);
 
                    // Keep track of maximum
                    // size of subtree
                    maxi = Math.Max(maxi, W.sz[W.Root(x)]);
                }
            }
 
            // Storing maximum cost of
            // subtree with a given AND
            ans = Math.Max(ans, maxi * i);
 
            // Separating components which are merged
            // during Union operation for next AND value.
            for (int x = i; x <= n; x = (i | (x + 1))) {
                W.sz[x] = 1;
                W.id[x] = x;
            }
        }
 
        return ans;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        for (int x = 0; x < N; x++)
            v.Add(new List<int>());
 
        int n, i;
 
        // Number of nodes
        n = 6;
 
        W.initial(n);
 
        Edge[] e = { new Edge(1, 2), new Edge(2, 3),
                     new Edge(3, 4), new Edge(3, 5),
                     new Edge(5, 6) };
 
        int q = e.Length;
 
        // Taking edges as input and put
        // them in adjacency list representation
        for (i = 0; i < q; i++) {
            int x, y;
            x = e[i].u;
            y = e[i].v;
            v[x].Add(y);
            v[y].Add(x);
        }
 
        // Initializing parent vertex of '1' as '1'
        p[1] = 1;
 
        // Call DFS to generate 'p' array
        dfs(1, -1);
 
        int ans = UnionUtil(n);
 
        Console.WriteLine("Maximum Cost = " + ans);
    }
}
 
// This code is contributed by phasing17


Javascript




// JS  code to find maximum possible cost
let N = 100010;
 
// Edge structure
class Edge {
    constructor(u, v)
    {
        this.u = u;
        this.v = v;
    }
}
 
// v : Adjacency list representation of Graph
//  p : stores parents of nodes '''
 
let v
    = new Array(N);
for (var i = 0; i < N; i++) {
    v[i] = [];
}
let p = new Array(N).fill(0);
 
// Weighted union-find with path compression
class wunionfind {
    constructor()
    {
        this.id = new Array(N + 1).fill(0);
        this.sz = new Array(N + 1).fill(0);
    }
 
    initial(n)
    {
        for (var i = 1; i <= n; i++) {
            this.id[i] = i;
            this.sz[i] = 1;
        }
    }
 
    Root(idx)
    {
 
        var i = idx;
 
        while (i != this.id[i]) {
            this.id[i] = this.id[this.id[i]];
            i = this.id[i];
        }
 
        return i;
    }
 
    Union(a, b)
    {
        var i = this.Root(a);
        var j = this.Root(b);
 
        if (i != j) {
            if (this.sz[i] >= this.sz[j]) {
                this.id[j] = i;
                this.sz[i] += this.sz[j];
                this.sz[j] = 0;
            }
            else {
                this.id[i] = j;
                this.sz[j] += this.sz[i];
                this.sz[i] = 0;
            }
        }
    }
}
 
let W
    = new wunionfind();
 
// DFS is called to generate parent of
// a node from adjacency list representation
function dfs(u, parent)
{
    for (var i = 0; i < v[u].length; i++) {
 
        var j = v[u][i];
 
        if (j != parent) {
            p[j] = u;
            dfs(j, u);
        }
    }
}
 
// Utility function for Union
function UnionUtil(n)
{
    let ans = 0;
 
    // Fixed 'i' as AND
    for (var i = 1; i <= n; i++) {
        let maxi = 1;
 
        // Generating supermasks of 'i'
        let x = i;
        while (x <= n) {
            let y = p[x];
 
            // Checking whether p[x] is
            // also a supermask of i.
            if ((y & i) == i) {
                W.Union(x, y);
 
                // Keep track of maximum
                // size of subtree
                maxi = Math.max(maxi, W.sz[W.Root(x)]);
            }
            x = (i | (x + 1));
        }
 
        // Storing maximum cost of
        // subtree with a given AND
        ans = Math.max(ans, maxi * i);
 
        // Separating components which are merged
        // during Union operation for next AND value.
        x = i;
        while (x <= n) {
            W.sz[x] = 1;
            W.id[x] = x;
            x = (i | (x + 1));
        }
    }
 
    return ans;
}
 
// Driver code
 
// Number of nodes
let n = 6;
 
W.initial(n);
 
let e = [
    new Edge(1, 2), new Edge(2, 3), new Edge(3, 4),
    new Edge(3, 5), new Edge(5, 6)
];
 
let q = e.length;
 
// Taking edges as input and put
// them in adjacency list representation
for (var i = 0; i < q; i++) {
    let x = e[i].u;
    let y = e[i].v;
    v[x].push(y);
    v[y].push(x);
}
 
// Initializing parent vertex of '1' as '1'
p[1] = 1;
 
// Call DFS to generate 'p' array
dfs(1, -1);
 
let ans = UnionUtil(n);
 
console.log("Maximum Cost =", ans)
 
 
// This code is contributed by phasing17


Output

Maximum Cost = 8

Time Complexity : Union in DSU takes O(1) time. Generating all supermasks takes O(3^k) time where k is the maximum number of bits which are ‘0’. DFS takes O(n). Overall time complexity is O(3^k+n).

Space Complexity: O(N)
The space complexity of the above code is O(N) as we are using a vector of size N and an array of size N.



Similar Reads

Disjoint Set Union on Trees
Given a tree and weights of nodes. Weights are non-negative integers. Task is to find maximum size of a subtree of a given tree such that all nodes are even in weights. Prerequisite : Disjoint Set Union Examples : Input : Number of nodes = 7 Weights of nodes = 1 2 6 4 2 0 3 Edges = (1, 2), (1, 3), (2, 4), (2, 5), (4, 6), (6, 7) Output : Maximum siz
11 min read
Extended Disjoint Set Union on Trees
Prerequisites: DFS, Trees, DSUGiven a tree with of N nodes from value 1 to N and E edges and array arr[] which denotes number associated to each node. You are also given Q queries which contains 2 integers {V, F}. For each query, there is a subtree with vertex V, the task is to check if there exists count of numbers associated with each node in tha
15 min read
Test case generator for Tree using Disjoint-Set Union
In this article, we will generate test cases such that given set edges form a Tree. Below are the two conditions of the Tree: It should have one less edge than the number of vertices.There should be no cycle in it. Approach: The idea is to run a loop and add one edge each time that is generated randomly, and for adding each edge we will check wheth
11 min read
Disjoint Set Union (Randomized Algorithm)
A Disjoint set union is an algorithm that is used to manage a collection of disjoint sets. A disjoint set is a set in which the elements are not in any other set. Also, known as union-find or merge-find. The disjoint set union algorithm allows you to perform the following operations efficiently: Find: Determine which set a given element belongs to.
15+ min read
Number of connected components of a graph ( using Disjoint Set Union )
Given an undirected graph G with vertices numbered in the range [0, N] and an array Edges[][] consisting of M edges, the task is to find the total number of connected components in the graph using Disjoint Set Union algorithm. Examples: Input: N = 4, Edges[][] = {{1, 0}, {2, 3}, {3, 4}}Output: 2Explanation: There are only 2 connected components as
7 min read
Introduction to Disjoint Set (Union-Find Algorithm)
What is a Disjoint set data structure?Two sets are called disjoint sets if they don't have any element in common, the intersection of sets is a null set. A data structure that stores non overlapping or disjoint subset of elements is called disjoint set data structure. The disjoint set data structure supports following operations: Adding new sets to
15+ min read
Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
Given a connected acyclic graph, a source vertex and a destination vertex, your task is to count the number of vertices between the given source and destination vertex by Disjoint Union Method . Examples: Input : 1 4 4 5 4 2 2 6 6 3 1 3 Output : 3 In the input 6 is the total number of vertices labeled from 1 to 6 and the next 5 lines are the connec
10 min read
Union By Rank and Path Compression in Union-Find Algorithm
In the previous post, we introduced union find algorithm and used it to detect cycles in a graph. We used the following union() and find() operations for subsets. C/C++ Code // Naive implementation of find int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]); } // Naive implementation of union() void Union(i
15+ min read
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Check whether a given graph contains a cycle or not. Example: Input: Output: Graph contains Cycle. Input: Output: Graph does not contain Cycle. Prerequisites: Disjoint Set (Or Union-Find), Union By Rank and Path CompressionWe have already discussed union-find to detect cycle. Here we discuss find by path compression, where it is slightly modified t
13 min read
Introduction to Generic Trees (N-ary Trees)
Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and the very first node's address will be stored in a s
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg