Maximum number of edges to be added to a tree so that it stays a Bipartite graph in C++

C++Server Side ProgrammingProgramming

Problem statement

A tree is always a Bipartite Graph as we can always break into two disjoint sets with alternate levels.

In other words, we always color it with two colors such that alternate levels have same color. The task is to compute the maximum no. of edges that can be added to the tree so that it remains Bipartite Graph.

Example

Tree edges are represented in vertex pairs as follows −

{1, 2}

{1, 3}

{2, 4}

{3, 5} then we need 2 more edges to keep it Bipartite Graph

  • In a coloring graph the graph {1, 4, 5} and {2, 3} from two different sets. Since, 1 is connected from both 2 and 3
  • We are left with edges 4 and 5. Since 4 is already connected to 2 and 5 to 3. Only remaining option is {4, 3} and {5, 2}

Algorithm

  • Do a simple DFS or BFS traversal of graph and color it with two colors
  • While coloring also keep track of counts of nodes colored with the two colors. Let the two counts be count_color0 and count_color1
  • Now we know maximum edges a bipartite graph can have are count_color0 x count_color1
  • We also know tree with n nodes has n-1 edges
  • So our answer is count_color0 x count_color1 – (n-1)

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
long long count_color[2];
void dfs(vector<int> graph[], int node, int parent, int color) {
   ++count_color[color];
   for (int i = 0; i < graph[node].size(); ++i) {
      if (graph[node][i] != parent) {
         dfs(graph, graph[node][i], node, !color);
      }
   }
}
int getMaxEdges(vector<int> graph[], int n) {
   dfs(graph, 1, 0, 0);
   return count_color[0] * count_color[1] - (n - 1);
}
int main() {
   int n = 5;
   vector<int> graph[n + 1];
   graph[1].push_back(2);
   graph[1].push_back(3);
   graph[2].push_back(4);
   graph[3].push_back(5);
   cout << "Maximum edges = " << getMaxEdges(graph, n) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Maximum edges = 2
raja
Published on 10-Jan-2020 07:55:14
Advertisements