假設存在一條邊 ,邊權為
從起點到 兩點的路徑長分別為
在 的時候,就可以更新起點到 的路徑
int dis[V] = INF;
bool in_tree[V] = false;
void dijkstra(int source){
priority_queue<node> pq;
pq.push((node){dis[source] = 0, source});
while(!pq.empty()){
if(in_tree[pq.top().vertex]){
pq.pop();
continue;
}
now = pq.top().vertex;
for(int i = 0; i < edge[now].size(); i++){
next = edge[now][i];
if(dis[now]+weight(now, next) < dis[next]){
pq.push((node){dis[next] = dis[now]+weight(now, next), next});
}
}
}
}全點對最短路徑
可以有負權
在一個路徑上,考慮一個一個中繼點,把「由 點中途經過前 點抵達 點的最短路徑長」拿來 DP,就得到轉移式:
複雜度
int weight[V][V], dis[V][V];
void floyd_warshall(){
for(int i = 0; i < V; i++)
dis[i][i] = 0;
for(int k = 0; k < V; k++)
for(int i = 0; i < V; i++)
for(int j = 0; j < V; j++)
if(dis[i][j] > dis[i][k] + dis[k][j])
dis[i][j] = dis[i][k] + dis[k][j];
}