# Disjoint Set Union on trees | Set 2

• Difficulty Level : Hard
• Last Updated : 10 Dec, 2020

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.```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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.

## CPP

 `// CPP code to find maximum possible cost``#include ``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);` `    ``// 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;` `    ``// Call DFS to generate 'p' array``    ``dfs(1, -1);` `    ``int` `ans = UnionUtil(n);``        ` `        ``printf``(``"Maximum Cost = %d\n"``, ans);` `    ``return` `0;``}`

## 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   `
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).

My Personal Notes arrow_drop_up