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 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 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 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# 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 |
// 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 |
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.