# Maximize the sum of products of the degrees between any two vertices of the tree in C++

C++Server Side ProgrammingProgramming

Given the task is to construct a tree with a given integer N such that, the sum of degree(x) * degree(y) for all ordered pairs (x,y) is maximum and x is not equal to y.

Input −N=5

Output −50

Explanation

   1
\
2
\
3
\
4
\
5
Degree of 1st node = 1
Degree of 2nd node = 2
Degree of 3rd node = 2
Degree of 4th node = 2
Degree of 5th node = 1

Product of all degrees for all ordered pairs (x, y) −

1st node = 1*2 + 1*2 + 1*2 + 1*1 = 7
2nd node = 2*1 + 2*2 + 2*2 + 2*1 = 12
3rd node = 2*1 + 2*2 + 2*2 + 2*1 = 12
4th node = 2*1 + 2*2 + 2*2 + 2*1 = 12
5th node = 1*2 + 1*2 + 1*2 + 1*1 = 7
Total sum = 50

Input −N=7

Output −122

## Approach used in the below program as follows

• Sum of degrees of all nodes in a tree is − (2 * N) – 2. Here N=number of nodes in the tree. In order to maximize the sum, the number of leaf nodes have to be minimized.

• Inside Max() function initialize int sum=0 and create nested loops initializing x=1 and y=1 having conditions x<N and y<N.

• Inside the nested loops first check if(x==y), if so then add continue; statement

• Else initialize int degree=2 and using an if statement check if(x==1 || x==n). If so then put degreeX=1. Then initialize int degree=2 and do the same for variable y

• Finally, before closing the loops, update the sum variable by writing − sum = (degreeX + degreeY)

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int Max(int N){
int sum = 0;
for (int x = 1; x <= N; x++){
for (int y = 1; y <= N; y++){
if (x == y)
continue;
//Initializing degree for node x to 2
int degreeX = 2;
//If x is the leaf node or the root node
if (x == 1 || x == N)
degreeX = 1;
//Initializing degree for node y to 2
int degreeY = 2;
//If y is the leaf node or the root node
if (y == 1 || y == N)
degreeY = 1;
//Updating sum
sum += (degreeX * degreeY);
}
}
return sum;
}
//Main function
int main(){
int N = 5;
cout << Max(N);
}

## Output

If we run the above code we will get the following output −

50
Published on 17-Aug-2020 08:58:29