-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-fuel-cost-to-report-to-the-capital.py
70 lines (63 loc) · 1.9 KB
/
minimum-fuel-cost-to-report-to-the-capital.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
# Time: O(n)
# Space: O(h)
# iterative dfs
class Solution(object):
def minimumFuelCost(self, roads, seats):
"""
:type roads: List[List[int]]
:type seats: int
:rtype: int
"""
def ceil_divide(a, b):
return (a+b-1)//b
def iter_dfs():
result = 0
stk = [(1, (0, -1, 0, [1]))]
while stk:
step, args = stk.pop()
if step == 1:
u, p, d, ret = args
stk.append((3, (d, ret)))
for v in adj[u]:
if v == p:
continue
new_ret = [1]
stk.append((2, (new_ret, ret)))
stk.append((1, (v, u, d+1, new_ret)))
elif step == 2:
new_ret, ret = args
ret[0] += new_ret[0]
elif step == 3:
d, ret = args
if d:
result += ceil_divide(ret[0], seats)
return result
adj = [[] for _ in xrange(len(roads)+1)]
for u, v in roads:
adj[u].append(v)
adj[v].append(u)
return iter_dfs()
# Time: O(n)
# Space: O(h)
# dfs
class Solution(object):
def minimumFuelCost(self, roads, seats):
"""
:type roads: List[List[int]]
:type seats: int
:rtype: int
"""
def ceil_divide(a, b):
return (a+b-1)//b
def dfs(u, p, d):
cnt = 1+sum(dfs(v, u, d+1) for v in adj[u] if v != p)
if d:
result[0] += ceil_divide(cnt, seats)
return cnt
adj = [[] for _ in xrange(len(roads)+1)]
for u, v in roads:
adj[u].append(v)
adj[v].append(u)
result = [0]
dfs(0, -1, 0)
return result[0]