中级农民
- 积分
- 208
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-5-11
- 最后登录
- 1970-1-1
|
Day 7 - 2019/02/11
743. Network Delay Time
这个题用到的算法感觉非常陌生,图论全忘了
至今还是想不通DFS的时间复杂度为什么是N的N次方。没走到一个点,面临N - 1个选择,一共要走N个点,于是就是N个N相乘,似乎是这样。
DFS算法:
使用int[]记录下一个点及其花费的时间。
构建Graph之后,把List of next node info 排个序,这样利于DFS中的剪枝。
使用一个Map,记录到达一个点需要的最短时间,这是这个题的关键。
在DFS过程中,如果到达此点的时间,比Map记录的最短时间长,那么就不需要走下去了。
如何判断是否到达所有点?将这个记录最短达到时间的Map用Integer.MAX_VALUE初始化,如果DFS完成的时候还是这个值,那就是没有走到过.
Dijkstra's single source shortest path Algorithm(权重图最短路径算法)
这个算法应用的场景:1)权重图;2)给定出发点;2)最短路径
这个算法的关键在于如何确定下一步要走的点: (贪心法,局部最优就是全局最优)
对List of next node这些点,使用edge的赋值将next点到原点的距离update一下(操作一),然后走向距离原点最近的那个点(操作二)
操作一:Decrease-Key
操作二:Extract-Min
本题的做法是:
用Map记录所有点目前的最短距离, 这同时也记录了目前走过的点,可以用来不走回头路.
用minHeap保存下一点的距离.这里的距离是指距离出发点的总距离,不要和edge的权重搞混了.
时间复杂度:
1. 不用minHeap是V平方
1) extract-min操作要遍历所有点,所以是O(V)时间。总时间是O(V^2)
2)
2. 如果这个graph是sparse的(E = o(V ^ 2 / logV)), 那么可以用binary minHeap或者Fibonacci Heap优化时间复杂度。
优化后是O((V + E)lgV):
1) 建堆是O(logV)时间 * V = O(VlogV)
2) 堆的poll操作花费logV时间,有多少条边就有多少poll操作,所以是ElogV时间.
一共就是O((V + E)logV) 可以看出来只有E = o(V^2/logV),这个才是优化的,不然还是V方。
不用minHeap的算法有一个while(true)循环,不知道怎么才能不用。
332. Reconstruct Itinerary
首先,这个题意保证了这是一个Eulerian circuit or Eulerian cycle(an Eulerian trail which starts and ends on the same vertex)
StefanPochmann用了Greedy DFS, building the route backwards when retreating。非常简洁明了
可是,面试的时候如何证明这个算法的正确性?如何把这个算法解释清楚?这个算法到底是Hierholzer算法吗?
维基百科上描述的Hierholzer算法:
By using a data structure such as a doubly linked list to maintain the set of unused edges incident to each vertex, to maintain the list of vertices on the current tour that have unused edges, and to maintain the tour itself, the individual operations of the algorithm (finding unused edges exiting each vertex, finding a new starting vertex for a tour, and connecting two tours that share a vertex) may be performed in constant time each, so the overall algorithm takes linear time, O(|E|)
并没有搞清楚上面的算法和这个Greedy DFS, building the route backwards when retreating是不是一回事。
硬着头皮写了一个DFS回溯的算法但是发现的testcase里还有这样的重复edge,这算欧拉回路吗?
[["EZE","AXA"],["TIA","ANU"],["ANU","JFK"],["JFK","ANU"],["ANU","EZE"],["TIA","ANU"],["AXA","TIA"],["TIA","JFK"],["ANU","TIA"],["JFK","TIA"]]
只好又改成用Map存所有的ticket,操作起来繁琐极了。最后也没有通过,是TLE。 最终还是完全copy了答案里的那个backtracking。 |
|