Dijkstra
01.Set dist(s,v)=INF for any v V;
Set dist(s,s)=0;
02.Now we build our CPQ(changeable priority queue): Q,with an item < v,dist(s,v) > for any v V;
item x=<x.id , x.key>
03.while Q not empty:
delete <u,dist(s,u)> from Q ; (which has minumun distance from s)
For v : if dist(s,v)>=dist(s,u)+weight(u,v),then
Relax edge (u,v);
//and tell Q that we changed the dist(s,,v)------
Decrease key of v in Q to new dist(s,v)
Priority Queue Interface
build(x):
build by starting empty and repeatly insert
Insert(x):
add item x;
Delete_Max():
delete & return max-key item;
Find_Max():
return max-key item;
1.Unsorted Array:
- insert takes O(1),//放尾巴就行
- but delete_max() takes O(n);//cuz have to scan through the whole Array to find where to insert
2.Sorted Array:
- insert takes O(n),
//cuz have to scan through the whole Array to find where to insert
- delete_max() takes O(1)
//cuz max is always the last
we want the best of these two world,which delete_max() is faster with unsorted array,and insert is faster with sorted array.
:(
we can't get constant time both
:)
but we can get logN time both
-------->which lead us to a datastructure Binary Heap
3.Binary Heap(is also Array)
- insert takes O(logN),
- delete_max() takes O(logN),too;