Maximize sum of MEX values of each node in an N-ary Tree
Last Updated :
03 May, 2023
Given an N-ary tree rooted at 1, the task is to assign values from the range [0, N - 1] to each node in any order such that the sum of MEX values of each node in the tree is maximized and print the maximum possible sum of MEX values of each node in the tree.
The MEX value of node V is defined as the smallest missing positive number in a tree rooted at node V.
Examples:
Input: N = 3, Edges[] = {{1, 2}, {1, 3}}
Output: 4
Explanation:

Assign value 0 to node 2, 1 to node 3 and 2 to node 1.
Therefore, the maximum sum of MEX of all nodes = MEX{1} + MEX{2} + MEX{3} = 3 + 1 + 0 = 4.
Input: N = 7, Edges[] = {1, 5}, {1, 4}, {5, 2}, {5, 3}, {4, 7}, {7, 6}}
Output: 13
Explanation:

Assign value 0 to node 6, 1 to node 7, 2 to node 4, 6 to node 1, 5 to node 5, 3 to node 2 and 4 to node 3.
Therefore, the maximum sum of MEX of all nodes = MEX{1} + MEX{2} + MEX{3} + MEX{4} + MEX{5} + MEX{6} + MEX{7} = 7 + 0 + 0 + 3 + 0 + 1 + 0 = 13.
Approach: The idea is to perform DFS Traversal on the given N-ary tree and find the sum of MEX for each subtree in the tree. Follow the steps below to solve the problem:
- Perform Depth First Search(DFS) on tree rooted at node 1.
- Initialize a variable mex with 0 and size with 1.
- Iterate through all children of the current node and perform the following operations:
- Recursively call the children of the current node and store the maximum sum of MEX among all subtree in mex.
- Increase the size of the tree rooted at the current node.
- Increase the value of mex by size.
- After completing the above steps, print the value of mex as the answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to create an N-ary Tree
void makeTree(vector<int> tree[],
pair<int, int> edges[],
int N)
{
// Traverse the edges
for (int i = 0; i < N - 1; i++) {
int u = edges[i].first;
int v = edges[i].second;
// Add edges
tree[u].push_back(v);
}
}
// Function to get the maximum sum
// of MEX values of tree rooted at 1
pair<int, int> dfs(int node,
vector<int> tree[])
{
// Initialize mex
int mex = 0;
int size = 1;
// Iterate through all children
// of node
for (int u : tree[node]) {
// Recursively find maximum sum
// of MEX values of each node
// in tree rooted at u
pair<int, int> temp = dfs(u, tree);
// Store the maximum sum of MEX
// of among all subtrees
mex = max(mex, temp.first);
// Increase the size of tree
// rooted at current node
size += temp.second;
}
// Resulting MEX for the current
// node of the recursive call
return { mex + size, size };
}
// Driver Code
int main()
{
// Given N nodes
int N = 7;
// Given N-1 edges
pair<int, int> edges[]
= { { 1, 4 }, { 1, 5 }, { 5, 2 }, { 5, 3 }, { 4, 7 }, { 7, 6 } };
// Stores the tree
vector<int> tree[N + 1];
// Generates the tree
makeTree(tree, edges, N);
// Returns maximum sum of MEX
// values of each node
cout << dfs(1, tree).first;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
static class pair
{
int first, second;
public pair(int first, int second)
{
this.first = first;
this.second = second;
}
}
// Function to create an N-ary Tree
static void makeTree(Vector<Integer> tree[],
pair edges[], int N)
{
// Traverse the edges
for(int i = 0; i < N - 1; i++)
{
int u = edges[i].first;
int v = edges[i].second;
// Add edges
tree[u].add(v);
}
}
// Function to get the maximum sum
// of MEX values of tree rooted at 1
static pair dfs(int node, Vector<Integer> tree[])
{
// Initialize mex
int mex = 0;
int size = 1;
// Iterate through all children
// of node
for(int u : tree[node])
{
// Recursively find maximum sum
// of MEX values of each node
// in tree rooted at u
pair temp = dfs(u, tree);
// Store the maximum sum of MEX
// of among all subtrees
mex = Math.max(mex, temp.first);
// Increase the size of tree
// rooted at current node
size += temp.second;
}
// Resulting MEX for the current
// node of the recursive call
return new pair(mex + size, size);
}
// Driver Code
public static void main(String[] args)
{
// Given N nodes
int N = 7;
// Given N-1 edges
pair edges[] = { new pair(1, 4),
new pair(1, 5),
new pair(5, 2),
new pair(5, 3),
new pair(4, 7),
new pair(7, 6) };
// Stores the tree
@SuppressWarnings("unchecked")
Vector<Integer>[] tree = new Vector[N + 1];
for(int i = 0; i < tree.length; i++)
tree[i] = new Vector<Integer>();
// Generates the tree
makeTree(tree, edges, N);
// Returns maximum sum of MEX
// values of each node
System.out.print((dfs(1, tree).first));
}
}
// This code is contributed by Princi Singh
Python3
# Python3 program for the above approach
# Function to create an N-ary Tree
def makeTree(tree, edges, N):
# Traverse the edges
for i in range(N - 1):
u = edges[i][0]
v = edges[i][1]
# Add edges
tree[u].append(v)
return tree
# Function to get the maximum sum
# of MEX values of tree rooted at 1
def dfs(node, tree):
# Initialize mex
mex = 0
size = 1
# Iterate through all children
# of node
for u in tree[node]:
# Recursively find maximum sum
# of MEX values of each node
# in tree rooted at u
temp = dfs(u, tree)
# Store the maximum sum of MEX
# of among all subtrees
mex = max(mex, temp[0])
# Increase the size of tree
# rooted at current node
size += temp[1]
# Resulting MEX for the current
# node of the recursive call
return [mex + size, size]
# Driver Code
if __name__ == '__main__':
# Given N nodes
N = 7
# Given N-1 edges
edges = [ [ 1, 4 ], [ 1, 5 ],
[ 5, 2 ], [ 5, 3 ],
[ 4, 7 ], [ 7, 6 ] ]
# Stores the tree
tree = [[] for i in range(N + 1)]
# Generates the tree
tree = makeTree(tree, edges, N)
# Returns maximum sum of MEX
# values of each node
print(dfs(1, tree)[0])
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
public class pair
{
public int first, second;
public pair(int first, int second)
{
this.first = first;
this.second = second;
}
}
// Function to create an N-ary Tree
static void makeTree(List<int> []tree,
pair []edges, int N)
{
// Traverse the edges
for(int i = 0; i < N - 1; i++)
{
int u = edges[i].first;
int v = edges[i].second;
// Add edges
tree[u].Add(v);
}
}
// Function to get the maximum sum
// of MEX values of tree rooted at 1
static pair dfs(int node, List<int> []tree)
{
// Initialize mex
int mex = 0;
int size = 1;
// Iterate through all children
// of node
foreach(int u in tree[node])
{
// Recursively find maximum sum
// of MEX values of each node
// in tree rooted at u
pair temp = dfs(u, tree);
// Store the maximum sum of MEX
// of among all subtrees
mex = Math.Max(mex, temp.first);
// Increase the size of tree
// rooted at current node
size += temp.second;
}
// Resulting MEX for the current
// node of the recursive call
return new pair(mex + size, size);
}
// Driver Code
public static void Main(String[] args)
{
// Given N nodes
int N = 7;
// Given N-1 edges
pair []edges = { new pair(1, 4),
new pair(1, 5),
new pair(5, 2),
new pair(5, 3),
new pair(4, 7),
new pair(7, 6) };
// Stores the tree
List<int>[] tree = new List<int>[N + 1];
for(int i = 0; i < tree.Length; i++)
tree[i] = new List<int>();
// Generates the tree
makeTree(tree, edges, N);
// Returns maximum sum of MEX
// values of each node
Console.Write((dfs(1, tree).first));
}
}
// This code is contributed by Amit Katiyar
JavaScript
<script>
// JavaScript program for the above approach
// Function to create an N-ary Tree
function makeTree(tree, edges, N)
{
// Traverse the edges
for (var i = 0; i < N - 1; i++) {
var u = edges[i][0];
var v = edges[i][1];
// Add edges
tree[u].push(v);
}
}
// Function to get the maximum sum
// of MEX values of tree rooted at 1
function dfs(node, tree)
{
// Initialize mex
var mex = 0;
var size = 1;
// Iterate through all children
// of node
tree[node].forEach(u => {
// Recursively find maximum sum
// of MEX values of each node
// in tree rooted at u
var temp = dfs(u, tree);
// Store the maximum sum of MEX
// of among all subtrees
mex = Math.max(mex, temp[0]);
// Increase the size of tree
// rooted at current node
size += temp[1];
});
// Resulting MEX for the current
// node of the recursive call
return [mex + size, size ];
}
// Driver Code
// Given N nodes
var N = 7;
// Given N-1 edges
var edges = [ [ 1, 4 ], [ 1, 5 ], [ 5, 2 ],
[ 5, 3 ], [ 4, 7 ], [ 7, 6 ] ];
// Stores the tree
var tree = Array.from(Array(N+1), ()=> Array());
// Generates the tree
makeTree(tree, edges, N);
// Returns maximum sum of MEX
// values of each node
document.write( dfs(1, tree)[0]);
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
MEX (Minimum Excluded) in Competitive Programming
MEX of a sequence or an array is the smallest non-negative integer that is not present in the sequence.Note: The MEX of an array of size N cannot be greater than N since the MEX of an array is the smallest non-negative integer not present in the array and array having size N can only cover integers
15+ min read
Minimum operations to make all Array elements 0 by MEX replacement
Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
5 min read
Minimum operations to make the MEX of the given set equal to x
Given a set of n integers, perform minimum number of operations (you can insert/delete elements into/from the set) to make the MEX of the set equal to x (that is given). Note:- The MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set
6 min read
Find the Prefix-MEX Array for given Array
Given an array A[] of N elements, the task is to create a Prefix-MEX array for this given array. Prefix-MEX array B[] of an array A[] is created such that MEX of A[0] till A[i] is B[i]. MEX of an array refers to the smallest missing non-negative integer of the array. Examples: Input: A[] = {1, 0, 2,
13 min read
Rearrange array elements to maximize the sum of MEX of all prefix arrays
Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximum MEX from all subarrays of length K
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {3, 2, 1, 4}, K = 2Output: 3Explanation:All subarrays havin
8 min read
Minimum operations for same MEX
Given an array 'arr' consisting of N arrays, each of size M, the task is to find the minimum number of operations required to make the Minimum Excluded Element (MEX) the same for all N arrays. You can perform the following task zero or more times: Choose one of the N arrays.Choose some non-negative
8 min read
Maximize MEX by adding or subtracting K from Array elements
Given an arr[] of size N and an integer, K, the task is to find the maximum possible value of MEX by adding or subtracting K any number of times from the array elements. MEX is the minimum non-negative integer that is not present in the array Examples: Input: arr[]={1, 3, 4}, K = 2Output: 2Explanati
7 min read
MEX of generated sequence of N+1 integers where ith integer is XOR of (i-1) and K
Given two integers N and K, generate a sequence of size N+1 where the ith element is (i-1)âK, the task is to find the MEX of this sequence. Here, the MEX of a sequence is the smallest non-negative integer that does not occur in the sequence. Examples: Input: N = 7, K=3Output: 8Explanation: Sequence
12 min read
Maximize sum of MEX values of each node in an N-ary Tree
Given an N-ary tree rooted at 1, the task is to assign values from the range [0, N - 1] to each node in any order such that the sum of MEX values of each node in the tree is maximized and print the maximum possible sum of MEX values of each node in the tree. The MEX value of node V is defined as the
9 min read