forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimize-the-total-price-of-the-trips.py
113 lines (105 loc) · 3.28 KB
/
minimize-the-total-price-of-the-trips.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
# Time: O(t * n)
# Space: O(n)
# iterative dfs, tree dp
class Solution(object):
def minimumTotalPrice(self, n, edges, price, trips):
"""
:type n: int
:type edges: List[List[int]]
:type price: List[int]
:type trips: List[List[int]]
:rtype: int
"""
def iter_dfs(u, target):
stk = [(1, (u, -1))]
while stk:
step, args = stk.pop()
if step == 1:
u, p = args
lookup[u] += 1
if u == target:
return
stk.append((2, (u,)))
for v in reversed(adj[u]):
if v == p:
continue
stk.append((1, (v, u)))
elif step == 2:
u = args[0]
lookup[u] -= 1
lookup[u] += 1
if u == target:
return True
for v in adj[u]:
if v == p:
continue
if dfs(v, u, target):
return True
lookup[u] -= 1
return False
def iter_dfs2():
result = [price[0]*lookup[0], (price[0]//2)*lookup[0]]
stk = [(1, (0, -1, result))]
while stk:
step, args = stk.pop()
if step == 1:
u, p, ret = args
for v in reversed(adj[u]):
if v == p:
continue
new_ret = [price[v]*lookup[v], (price[v]//2)*lookup[v]]
stk.append((2, (new_ret, ret)))
stk.append((1, (v, u, new_ret)))
elif step == 2:
new_ret, ret = args
ret[0] += min(new_ret)
ret[1] += new_ret[0]
return min(result)
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
lookup = [0]*n
for u, v in trips:
iter_dfs(u, v)
return iter_dfs2()
# Time: O(t * n)
# Space: O(n)
# dfs, tree dp
class Solution2(object):
def minimumTotalPrice(self, n, edges, price, trips):
"""
:type n: int
:type edges: List[List[int]]
:type price: List[int]
:type trips: List[List[int]]
:rtype: int
"""
def dfs(u, p, target):
lookup[u] += 1
if u == target:
return True
for v in adj[u]:
if v == p:
continue
if dfs(v, u, target):
return True
lookup[u] -= 1
return False
def dfs2(u, p):
full, half = price[u]*lookup[u], price[u]//2*lookup[u]
for v in adj[u]:
if v == p:
continue
f, h = dfs2(v, u)
full += min(f, h)
half += f
return full, half
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
lookup = [0]*n
for u, v in trips:
dfs(u, -1, v)
return min(dfs2(0, -1))