-
Notifications
You must be signed in to change notification settings - Fork 3
/
q1519.py
78 lines (71 loc) · 2.45 KB
/
q1519.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/python3
from collections import defaultdict
from typing import List
class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
listOfDic = list()
for i in range(n):
listOfDic.append({})
listOfDic[i][labels[i]] = 1
edgeFlag = [True for _ in range(n)]
edgeFlag[0] = False
for edge in edges:
if edgeFlag[edge[0]] and not edgeFlag[edge[1]]:
temp = edge[0]
edge[0] = edge[1]
edge[1] = temp
if edgeFlag[edge[1]]:
edgeFlag[edge[1]] = False
for edge in reversed(edges):
node1 = edge[0]
node2 = edge[1]
for key in listOfDic[node2].keys():
if key in listOfDic[node1]:
listOfDic[node1][key] += listOfDic[node2][key]
else:
listOfDic[node1][key] = listOfDic[node2][key]
result = list()
for i in range(n):
result.append(listOfDic[i][labels[i]])
return result
# class Solution:
# def dfs(self, flags, index, edgeDic, listOfDic, labels, result):
# if flags[index]:
# return
# flags[index] = True
# result.append(listOfDic[index][labels[index]])
# for index in edgeDic[index]:
# self.dfs(flags, index, edgeDic, listOfDic, labels, result)
#
# def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
# listOfDic = list()
#
# for i in range(n):
# dic = defaultdict()
# listOfDic.append(dic)
# listOfDic[i][labels[i]] = 1
#
# edgeDic = defaultdict(list)
# for edge in edges:
# edgeDic[edge[0]].append(edge[1])
#
# for edge in reversed(edges):
# node1 = edge[0]
# node2 = edge[1]
# for key in listOfDic[node2].keys():
# if key in listOfDic[node1]:
# listOfDic[node1][key] += listOfDic[node2][key]
# else:
# listOfDic[node1][key] = listOfDic[node2][key]
#
# result = list()
# flags = [False for _ in range(n)]
# for i in range(n):
# self.dfs(flags, i, edgeDic, listOfDic, labels, result)
# return result
solu = Solution()
n = 4
edges = [[0,2],[0,3],[1,2]]
labels = "aeed"
result = solu.countSubTrees(n, edges, labels)
print(result)