fibonacci,shortest paths(DP)
dynamic programming --weried term,no deep meaning
- DAG
- algorithem design technique, optimization problem(min path)
- exhaustive searsh but do in clear way, so DP like careful brute force
fibonacci problem:
- naive
for : n =1,2 => 1else f(n) =f(n-1) +f(n-2)
>=O(2^(n/2))
- memorized transformation(up-to-bottom)
memo={}
fib(n):
if n in memo =>memo[n] if n<=2 =>1else f(n) = f(n-1)+f(n-2) put in memo[n]
return f
O(n)
- memorize and re-use solutions to subproblems
time = subproblems * time spend on persubproblem
key : ignore memorized recursions
- bottom-to-up DP
fib ={} for k in range(1,n+1): k<= 2=>f =1 else f = f[k-1]+f[k-2] fib[k] = f return fib[n]
look into a table or array which you stored previous fib
-
shortest paths from s->v
try all the answers and take the best one(guess if don't know the answer)
- naive
shortest(s,v) =shortest(s,u) + weight(u,v) //u is the neighbor of v
//u has indegree(v) possiblities
exponential
2. memoize
if shortest(s,v) exsited return else shortest(s,v) =shortest(s,u) + weight(u,v)
//u has indegree(v) possiblities
infinite time for graphs with cycles
for DAGs(directed acyclic graph):
time for subpro = indegree(v)+1 - incoming of v +1
total time is Θ(E+ v)-- number of edges+v
3. how to be not infinite
subproblem dependecies should be acyclic.
- or how to make cyclic problem acyclic
- no negative weight cycles
- reduce your graph to k copies of graph
- make all edges go from each layer to next layer
- define shortestk(s,v) : weight of shortest s->v path that uses <=k edges total
shortestk(k,s,v) =shortestk(k-1,s,u) +weight(u,v)
Θ(Ev)
!!: DP = recursion +memorization +guessing for DAGs
From satrys,
Kristen wang