Dado un árbol, y el costo de un subárbol se define como |S|*Y(S) donde |S| es el tamaño del subárbol y AND(S) es AND bit a bit de todos los índices de los Nodes del subárbol, la tarea es encontrar el costo máximo del posible subárbol.
Requisito previo : ejemplos de unión de conjuntos disjuntos :
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.
Enfoque: la estrategia es fijar el AND y encontrar el tamaño máximo de un subárbol de modo que el AND de todos los índices sea igual al AND dado. Supongamos que fijamos AND como ‘A’. En la representación binaria de A, si el i-ésimo bit es ‘1’, entonces todos los índices (Nodes) del subárbol requerido deberían tener ‘1’ en la i-ésima posición en la representación binaria. Si el i-ésimo bit es ‘0’, entonces los índices tienen ‘0’ o ‘1’ en la i-ésima posición. Eso significa que todos los elementos del subárbol son supermáscaras de A. Todas las supermáscaras de A se pueden generar en tiempo O(2^k), donde ‘k’ es el número de bits que son ‘0’ en A.
Ahora, el tamaño máximo del subárbol con un Y ‘A’ dado se puede encontrar usando DSU en el árbol. Sea ‘u’ la supermáscara de A y ‘p[u]’ el padre de u. Si p[u] también es una supermáscara de A, entonces tenemos que actualizar la DSU fusionando los componentes de u y p[u]. Simultáneamente, también tenemos que realizar un seguimiento del tamaño máximo del subárbol. DSU nos ayuda a hacerlo. Será más claro si observamos el siguiente código.
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
Maximum Cost = 8
Complejidad de tiempo: la unión en DSU toma O (1) tiempo. La generación de todas las supermáscaras lleva un tiempo O(3^k), donde k es el número máximo de bits que son ‘0’. DFS toma O(n). La complejidad temporal total es O(3^k+n).
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA