3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
链式前向星实现:(数据规模较小时速度比不上邻接矩阵)
#include <stdio.h> #include <string.h> #define maxn 202 #define maxm 2002 int head[maxn], dist[maxn]; struct Node{ int to, w, next; } edge[maxm]; bool vis[maxn]; int getNext(int n) { int i, u = -1, tmp = -1; for(i = 0; i < n; ++i) if(!vis[i] && dist[i] != -1 && (dist[i] < tmp || tmp == -1)){ tmp = dist[i]; u = i; } return u; } void Dijkstra(int v, int u, int n) { int i, tmp; dist[v] = 0; while(v != -1){ for(i = head[v]; i != -1; i = edge[i].next){ if(vis[edge[i].to]) continue; tmp = dist[v] + edge[i].w; if(dist[edge[i].to] == -1 || tmp < dist[edge[i].to]) dist[edge[i].to] = tmp; } vis[v] = true; v = getNext(n); if(vis[u]) return; } } int main() { int n, m, i, a, b, c; while(scanf("%d%d", &n, &m) != EOF){ memset(head, -1, sizeof(head)); memset(vis, 0, sizeof(vis)); memset(dist, -1, sizeof(dist)); for(i = 0; i < m; ++i){ scanf("%d%d%d", &a, &b, &c); edge[i].to = b; edge[i].w = c; edge[i].next = head[a]; head[a] = i; edge[m+i].to = a; edge[m+i].w = c; edge[m+i].next = head[b]; head[b] = m + i; } scanf("%d%d", &a, &b); Dijkstra(a, b, n); printf("%d\n", dist[b]); } return 0; }
邻接矩阵实现:
#include <stdio.h> #include <string.h> #define maxn 202 const int maxint = 100000000; int n, m; int dist[maxn], map[maxn][maxn]; bool vis[maxn]; int getNextNode() { int i, tmp = maxint, u = -1; for(i = 0; i < n; ++i){ if(dist[i] != -1 && !vis[i] && dist[i] < tmp){ tmp = dist[i]; u = i; } } return u; } void Dijkstra(int start, int end) { memset(dist, -1, sizeof(dist)); memset(vis, 0, sizeof(vis)); int i, tmp, u; dist[start] = 0; vis[start] = true; for(i = 0; i < n; ++i){ if(map[start][i] != -1) dist[i] = map[start][i]; } u = getNextNode(); while(u != -1){ for(i = 0; i < n; ++i){ if(map[u][i] != -1 && !vis[i]){ tmp = dist[u] + map[u][i]; if(dist[i] == -1 || dist[i] > tmp) dist[i] = tmp; } } vis[u] = true; u = getNextNode(); } } int main() { int i, a, b, x, s, t; while(scanf("%d%d", &n, &m) != EOF){ memset(map, -1, sizeof(map)); for(i = 0; i < m; ++i){ scanf("%d%d%d", &a, &b, &x); if(map[a][b] != -1 && x > map[a][b]) continue; map[a][b] = map[b][a] = x; } scanf("%d%d", &s, &t); Dijkstra(s, t); printf("%d\n", dist[t]); } return 0; }