1. 程式人生 > >Dijstra單源最短路【模板】(裸的,鄰接矩陣)

Dijstra單源最短路【模板】(裸的,鄰接矩陣)

Dijstra單源最短路【模板】(裸的,鄰接矩陣)

例題:洛谷-熱浪

附:最詳細的講解

程式碼:

#include <iostream>
#include <cstdio>

using namespace std;

const int inf = 1e9 + 7;
const int N = 2357;

int n,m,s,e[N][N],dis[N],u,v,w;
bool vis[N];

int main()
{
	scanf("%d%d%d",&n,&m,&s);
	for(int i = 1; i <=
n; i ++) for(int j = 1; j <= n; j ++) if(i != j)e[i][j] = inf; for(int i = 1; i <= m; i ++) { scanf("%d%d%d",&u,&v,&w); e[u][v] = min(e[u][v],w); } for(int i = 1; i <= n; i ++) dis[i] = e[s][i]; vis[s] = 1; for(int i = 1; i < n; i ++) { int minn = inf; for
(int j = 1; j <= n; j ++) { if(dis[j] < minn && vis[j] == 0) { minn = dis[j]; u = j; } } vis[u] = 1; for(v = 1; v <= n; v ++) dis[v] = min(dis[v],dis[u]+e[u][v]); } for(int i = 1; i <= n; i ++) printf("%d ",dis[i]); return 0; }

時間複雜度:Θ(n^2)