Given the edges of a tree and a sum S. The task is to assign weights to the all the edges of the tree such that the longest path in terms of weights is minimized and the total sum of weights assigned should be S and print the longest path’s weight.
Note: Edges can be assigned any weights in range [0, S] and can be fractional also.
Examples:
Input: 1
/ | \
2 3 4
S = 3
Output: 2
All the edges can be assigned weights of 1, so
the longest path will in terms of weight will be
2--1--4 or 2--1--3
Input: 1
/
2
/ \
3 4
/ \
5 6
S = 1
Output: 0.50
Assign the given below weights to edges.
1--2: 0.25
2--3: 0.25
2--4: 0
4--5: 0.25
4--6: 0.25
Hence the longest path in terms of weight is 1--2--3
or 1--2--4--5 or 1--2--4--6.
Approach: The property of a tree that a path can have a maximum of two leaf nodes in it can be used to solve the above problem. So if we assign weights only to the edges connecting the leaf nodes, and assign other edges to 0. Then every edge connecting to the leaf nodes will be assigned s/(number of leaf nodes). Since a path can contain a maximum of two leaf nodes, hence the longest path will be 2 * (s/number of leaf nodes).
Below is the implementation of the above approach:
C++
// C++ program to assign weights to edges to // minimize the longest path in terms of weight #include <bits/stdc++.h> using namespace std; // Function to add edges void addEdges(int u, int v, vector<int> adj[]) { adj[u].push_back(v); adj[v].push_back(u); } // Function that assigns weights // and returns the longest path long double longestPath(vector<int> adj[], int s, int n) { int cnt = 0; for (int i = 1; i <= n; i++) { if (adj[i].size() == 1) cnt++; } long double ans = 2.0 * (long double)(s / (long double)(cnt)); return ans; } // Driver Code int main() { int n = 4; // Create an adjacency list // to store tree vector<int> adj[n + 1]; // Add edges addEdges(1, 2, adj); addEdges(1, 3, adj); addEdges(1, 4, adj); // Given Sum int s = 3; // Function that prints the // longest path in terms of weights cout << longestPath(adj, s, n); } |
Java
// Java program to assign weights to edges to // minimize the longest path in terms of weight import java.util.*; class GFG { // Function to add edges static void addEdges(int u, int v, Vector<Integer> adj[]) { adj[u].add(v); adj[v].add(u); } // Function that assigns weights // and returns the longest path static double longestPath(Vector<Integer> adj[], int s, int n) { int cnt = 0; for (int i = 1; i <= n; i++) { if (adj[i].size() == 1) cnt++; } double ans = 2.0 * (double) (s / (double) (cnt)); return ans; } // Driver Code public static void main(String[] args) { int n = 4; // Create an adjacency list // to store tree Vector<Integer>[] adj = new Vector[n + 1]; for (int i = 0; i < n + 1; i++) adj[i] = new Vector<Integer>(); // Add edges addEdges(1, 2, adj); addEdges(1, 3, adj); addEdges(1, 4, adj); // Given Sum int s = 3; // Function that prints the // longest path in terms of weights System.out.print(longestPath(adj, s, n)); } } // This code is contributed by Rajput-Ji |
Python3
# Python3 program to assign weights to # edges to minimize the longest path # in terms of weight # Function to add edges def addEdges(u, v, adj): adj[u].append(v) adj[v].append(u) # Function that assigns weights # and returns the longest path def longestPath(adj, s, n): cnt = 0 for i in range(1, n + 1): if len(adj[i]) == 1: cnt += 1 ans = 2 * (s / cnt) return ans # Driver Code if __name__ == "__main__": n = 4 # Create an adjacency list # to store tree adj = [[] for i in range(n + 1)] # Add edges addEdges(1, 2, adj) addEdges(1, 3, adj) addEdges(1, 4, adj) # Given Sum s = 3 # Function that prints the # longest path in terms of weights print(longestPath(adj, s, n)) # This code is contributed by Rituraj Jain |
C#
// C# program to assign weights to edges to // minimize the longest path in terms of weight using System; using System.Collections.Generic; class GFG { // Function to add edges static void addEdges(int u, int v, List<int> []adj) { adj[u].Add(v); adj[v].Add(u); } // Function that assigns weights // and returns the longest path static double longestPath(List<int> []adj, int s, int n) { int cnt = 0; for (int i = 1; i <= n; i++) { if (adj[i].Count == 1) cnt++; } double ans = 2.0 * (double) (s / (double) (cnt)); return ans; } // Driver Code public static void Main(String[] args) { int n = 4; // Create an adjacency list // to store tree List<int>[] adj = new List<int>[n + 1]; for (int i = 0; i < n + 1; i++) adj[i] = new List<int>(); // Add edges addEdges(1, 2, adj); addEdges(1, 3, adj); addEdges(1, 4, adj); // Given Sum int s = 3; // Function that prints the // longest path in terms of weights Console.Write(longestPath(adj, s, n)); } } // This code is contributed by Rajput-Ji |
2
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.
Recommended Posts:
- Tree with N nodes and K leaves such that distance between farthest leaves is minimized
- Count nodes having Bitwise XOR of all edges in their path from the root equal to K
- Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal
- Number of distinct pair of edges such that it partitions both trees into same subsets of nodes
- Color tree with minimum colors such that colors of edges incident to a vertex are different
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Longest path in an undirected tree
- Print the longest leaf to leaf path in a Binary tree
- Longest Path with Same Values in a Binary Tree
- Length of longest straight path from a given Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Sum of nodes on the longest path from root to leaf node
- Possible edges of a tree for given diameter, height and vertices
- Number of edges in mirror image of Complete binary tree
- Number of edges in a perfect binary tree with N levels
- Minimum number of edges required to be removed from an Undirected Graph to make it acyclic
- Maximum number of edges to be removed to contain exactly K connected components in the Graph
- Right sibling of each node in a tree given as array of edges
- Number of unique paths in tree such that every path has a value greater than K
- Find the maximum sum leaf to root path in a Binary Tree
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.

