forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-path-with-different-adjacent-characters.py
123 lines (110 loc) · 3.74 KB
/
longest-path-with-different-adjacent-characters.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# Time: O(n)
# Space: O(w)
import collections
# tree, bfs, topological sort
class Solution(object):
def longestPath(self, parent, s):
"""
:type parent: List[int]
:type s: str
:rtype: int
"""
def topological_sort(s, adj, in_degree):
result = 1
top2 = collections.defaultdict(lambda:[0]*2)
q = [(i, 1) for i, d in enumerate(in_degree) if not d]
while q:
new_q = []
for (u, l) in q:
for v in adj[u]:
if s[v] != s[u]:
if l > top2[v][0]:
top2[v][0], top2[v][1] = l, top2[v][0]
elif l > top2[v][1]:
top2[v][1] = l
in_degree[v] -= 1
if in_degree[v]:
continue
new_q.append((v, top2[v][0]+1))
result = max(result, top2[v][0]+top2[v][1]+1)
del top2[v]
q = new_q
return result
adj = [[] for _ in xrange(len(s))]
in_degree = [0]*len(s)
for i in xrange(1, len(parent)):
adj[i].append(parent[i])
in_degree[parent[i]] += 1
return topological_sort(s, adj, in_degree)
# Time: O(n)
# Space: O(h)
# tree, dfs
class Solution2(object):
def longestPath(self, parent, s):
"""
:type parent: List[int]
:type s: str
:rtype: int
"""
def iter_dfs(s, adj):
result = 0
stk = [(1, (0, [0]))]
while stk:
step, args = stk.pop()
if step == 1:
u, ret = args
top2 = [0]*2
stk.append((4, (top2, ret)))
stk.append((2, (u, 0, top2, ret)))
elif step == 2:
u, i, top2, ret = args
if i == len(adj[u]):
continue
ret2 = [0]
stk.append((3, (u, i, top2, ret2)))
stk.append((1, (adj[u][i], ret2)))
elif step == 3:
u, i, top2, ret2 = args
if s[adj[u][i]] != s[u]:
if ret2[0] > top2[0]:
top2[0], top2[1] = ret2[0], top2[0]
elif ret2[0] > top2[1]:
top2[1] = ret2[0]
stk.append((2, (u, i+1, top2, ret)))
elif step == 4:
top2, ret = args
result = max(result, top2[0]+top2[1]+1)
ret[0] = top2[0]+1
return result
adj = [[] for _ in xrange(len(s))]
for i in xrange(1, len(parent)):
adj[parent[i]].append(i)
return iter_dfs(s, adj)
# Time: O(n)
# Space: O(h)
# tree, dfs
class Solution3(object):
def longestPath(self, parent, s):
"""
:type parent: List[int]
:type s: str
:rtype: int
"""
def dfs(s, adj, u, result):
top2 = [0]*2
for v in adj[u]:
l = dfs(s, adj, v, result)
if s[v] == s[u]:
continue
if l > top2[0]:
top2[0], top2[1] = l, top2[0]
elif l > top2[1]:
top2[1] = l
result[0] = max(result[0], top2[0]+top2[1]+1)
return top2[0]+1
adj = [[] for _ in xrange(len(s))]
for i in xrange(1, len(parent)):
adj[parent[i]].append(i)
result = [0]
dfs(s, adj, 0, result)
return result[0]