File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ # All trees are bipartite graphs
2+ # Reference - https://www.geeksforgeeks.org/maximum-number-edges-added-tree-stays-bipartite-graph/
3+
4+ # Traverse the tree (dfs or bfs) and color nodes with two colors and count each like
5+ # count_color1 and count_color2. Then the max edges that the graph can have are
6+ # count_color1 * count_color2, and the max edges of a tree are n-1
7+
8+ # Therefore the answer is = count_color1 * count_color2 - (n-1)
9+
10+ class Graph :
11+
12+ def __init__ (self , vertices ):
13+ self .vertices = vertices
14+ self .graph = [[] for i in range (vertices )]
15+
16+
17+ def add_edge (self , u , v ):
18+ self .graph [u ].append (v )
19+
20+
21+ def bfs (self , s ):
22+ visited = [False ] * self .vertices
23+ color_count = [0 , 0 ]
24+
25+ colors = [- 1 ] * self .vertices
26+ colors [s ] = 1
27+
28+ queue = []
29+
30+ queue .append (s )
31+ visited [s ] = True
32+
33+ while queue :
34+ u = queue .pop (0 )
35+
36+ for v in self .graph [u ]:
37+ if colors [v ] == - 1 : # This is a tree. So not visited and not colored is same as there is no cycle
38+ colors [v ] = 1 - colors [u ]
39+ queue .append (v )
40+ color_count [colors [v ]] += 1
41+ visited [v ] = True
42+
43+ # Counting the max number of edges for graph
44+ graph_edges = color_count [0 ] * color_count [1 ]
45+
46+ return graph_edges
47+
48+
49+ # Number of tree nodes
50+ n = 5
51+
52+ g = Graph (5 )
53+ g .add_edge (1 , 2 )
54+ g .add_edge (1 , 3 )
55+ g .add_edge (2 , 4 )
56+ g .add_edge (3 , 5 )
You can’t perform that action at this time.
0 commit comments