# Disjoint Set Union on trees | Set 2

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.

`// 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; ` `} ` |

*chevron_right*

*filter_none*

**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).

## Recommended Posts:

- Disjoint Set Union on trees | Set 1
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
- Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
- Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
- Job Sequencing Problem | Set 2 (Using Disjoint Set)
- Find the number of Islands | Set 2 (Using Disjoint Set)
- Disjoint Set Data Structures (Java Implementation)
- Maximum Possible Edge Disjoint Spanning Tree From a Complete Graph
- AA Trees | Set 1 (Introduction)
- Check if two trees are Mirror
- 2-3 Trees | (Search and Insert)
- Combinatorics on ordered trees
- DP on Trees | Set-3 ( Diameter of N-ary Tree )
- Enumeration of Binary Trees

This article is contributed by **fsociety99**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.