Dijsktra
贪心原则
1、从源点出发寻找可达的点,更新dist值,标记为已访问
2、从更新过值得点中选最dist值最小且未被访问过的点,寻找可达的未访问点,更新dist值,当前点标记为已访问
3、重复第二步最多n-1次,就能得到源点到各点的最短距离
邻接矩阵实现
时间复杂度O(n^2),n为顶点个数
根据dijsktra的性质,d[j] = min(d[i]+g[i][j], d[j]),所以path数组是记录当前点的前驱。
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 3000 + 10;
const int INF = 0x3f3f3f3f;
int n, m, st;
int dist[maxn];
int path[maxn];
int g[maxn][maxn];
bool visited[maxn];
void Dijsktra()
{
memset(visited, false, sizeof(visited));
for(int i = 0; i < n; i++) dist[i] = INF;
dist[st] = 0;
path[st] = -1;
for(int k = 0; k < n; k++){
int Min = INF;
int pos;
for(int i = 0; i < n; i++){
if(!visited[i] && dist[i] < Min){
Min = dist[i];
pos = i;
}
}
visited[pos] = true;
for(int i = 0; i < n; i++){
if(!visited[i] && g[pos][i] != INF && (Min + g[pos][i] < dist[i])){
dist[i] = Min + g[pos][i];
path[i] = pos;
}
}
}
}
void showPath(int ed)
{
int i = ed;
printf("%d ",ed);
while(path[i] != -1){
printf("%d ",path[i]);
i = path[i];
}
printf("\t-->dis : %d\n",dist[ed]);
}
int main()
{
while(~scanf("%d%d%d", &n, &m, &st)){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
g[i][j] = INF;
}
g[i][i] = 0;
}
for(int i = 0; i < m; i++){
int a, b, c;
scanf("%d%d%d",&a, &b, &c);
g[a][b] = c;
}
Dijsktra();
for(int i = 0; i < n; i++){
printf("%d-->%d : ", st, i);
showPath(i);
}
}
return 0;
}
邻接表实现,优先队列优化
时间复杂度为O( m*log(n) ),n为顶点数,m为边数
优化的是每要次寻找的dist里的最小值,邻接表更新边O(m)
代码是白书上模板:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <utility>
using namespace std;
const int maxn = 3000 + 10;
const int INF = 0x3f3f3f3f;
struct edge{
int to, cost;
};
typedef pair<int, int> P;
int n, m;
int d[maxn];
int path[maxn];
bool visited[maxn];
vector<edge> G[maxn];
void dijsktra(int s, int V)
{
priority_queue<P, vector<P>, greater<P> > que;
for(int i = 0; i < V; i++) d[i] = INF;
memset(visited, 0, sizeof(visited));
d[s] = 0;
que.push(P(0, s));
while(!que.empty()){
P p = que.top(); que.pop();
int v =p.second;
if(d[v] < p.first) continue;
for(int i = 0; i < G[v].size(); i++){
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost){
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
}
}
int main()
{
int st;
while(~scanf("%d%d%d", &n, &m, &st)){
for(int i = 0; i < n; i++) G[i].clear();
for(int i = 0; i < m; i++){
edge e; int a;
scanf("%d%d%d",&a, &e.to, &e.cost);
G[a].push_back(e);
}
dijsktra(st, n);
for(int i = 0; i < n; i++) printf("%d ",d[i]);
printf("\n");
}
return 0;
}