

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Assign weights to edges such that longest path in terms of weights is minimized in C++
Here we will see one problem, in this problem one edge of a tree and a sum S is given. The task is to assign weights to all other weights, such that longest path in terms of weight is minimized. The sum of weights assigned to it is same as ‘S’.
The approach is simple. The property of a tree that a path can have a maximum of two leaf nodes in it. That will be used to get the solution. So if we assign weights only to the edges connecting the leaf nodes, and assign other edges to 0. Then every edge which is connecting to the leaf nodes will be assigned as
Since a path can contain a maximum of two leaf nodes, hence the longest path will be
Example
#include<iostream> #include<vector> using namespace std; void insertEdge(int u, int v, vector<int> adj[]) { adj[u].push_back(v); adj[v].push_back(u); } long double pathLength(vector<int> adj[], int sum, int n) { int count = 0; for (int i = 1; i <= n; i++) { if (adj[i].size() == 1) count++; } long double ans = 2.0 * (long double)(sum / (long double)(count)); return ans; } int main() { int n = 6; vector<int> adj[n + 1]; insertEdge(1, 2, adj); insertEdge(2, 3, adj); insertEdge(2, 4, adj); insertEdge(4, 5, adj); insertEdge(4, 6, adj); int sum = 1; cout << pathLength(adj, sum, n); }
Output
0.5
- Related Questions & Answers
- Sorting according to weights of numbers in JavaScript
- Sorting an array that contains the value of some weights using JavaScript
- Single-Source Shortest Paths, Nonnegative Weights
- Single-Source Shortest Paths, Arbitrary Weights
- Balance pans using given weights that are powers of a number in C++ program
- How to create a histogram using weights in R?
- How can Keras be used to manually save the weights using Python?
- Longest path in 2-D that contains increasing sequence in JavaScript
- Shortest path with exactly k Edges
- How can Tensorflow be used to save and load weights for MNIST dataset?
- How can Keras be used to save weights for model after specific number of epochs in Python?
- Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal in C++
- Check if item can be measured using a scale and some weights in Python
- C++ Program to check given candies can be split with equal weights or not
- How can Keras be used to create a callback and save the weights using Python?
Advertisements