Assign weights to edges such that longest path in terms of weights is minimized in C++

C++Server Side ProgrammingProgramming

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


using namespace std;
void insertEdge(int u, int v, vector<int> adj[]) {
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)
   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);


Updated on 20-Aug-2019 07:47:16