File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ You are given a tree(a simple connected graph with no cycles). The tree has N
3+ nodes numbered from 1 to N and is rooted at node 1.
4+
5+ Find the maximum number of edges you can remove from the tree to get a forest
6+ such that each connected component of the forest contains an even number of
7+ nodes.
8+
9+ Constraints
10+ 2 <= 2 <= 100
11+
12+ Note: The tree input will be such that it can always be decomposed into
13+ components containing an even number of nodes.
14+ """
15+ # pylint: disable=invalid-name
16+ from collections import defaultdict
17+
18+
19+ def dfs (start ):
20+ """DFS traversal"""
21+ # pylint: disable=redefined-outer-name
22+ ret = 1
23+ visited [start ] = True
24+ for v in tree .get (start ):
25+ if v not in visited :
26+ ret += dfs (v )
27+ if ret % 2 == 0 :
28+ cuts .append (start )
29+ return ret
30+
31+
32+ def even_tree ():
33+ """
34+ 2 1
35+ 3 1
36+ 4 3
37+ 5 2
38+ 6 1
39+ 7 2
40+ 8 6
41+ 9 8
42+ 10 8
43+ On removing edges (1,3) and (1,6), we can get the desired result 2.
44+ """
45+ dfs (1 )
46+
47+
48+ if __name__ == '__main__' :
49+ n , m = 10 , 9
50+ tree = defaultdict (list )
51+ visited = {}
52+ cuts = []
53+ count = 0
54+ edges = [
55+ (2 , 1 ),
56+ (3 , 1 ),
57+ (4 , 3 ),
58+ (5 , 2 ),
59+ (6 , 1 ),
60+ (7 , 2 ),
61+ (8 , 6 ),
62+ (9 , 8 ),
63+ (10 , 8 ),
64+ ]
65+ for u , v in edges :
66+ tree [u ].append (v )
67+ tree [v ].append (u )
68+ even_tree ()
69+ print len (cuts ) - 1
You can’t perform that action at this time.
0 commit comments