Dijkstra模板 (n^2)
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<string.h>
#include<limits.h>
#include<vector>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 505;
int a[maxn][maxn],vis[maxn],dist[maxn];
int n,m;
int main(void) {
void dijkstra();
memset(a,0x3f,sizeof(a));
memset(dist,0x3f,sizeof(dist)); // 刚开始每个顶点之间的距离都设置为无穷大
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&m);
int x,y,w;
for(int i = 1; i <= m; i ++) {
scanf("%d%d%d",&x,&y,&w);
a[x][y] = min(a[x][y],w);
}
dijkstra();
if(dist[n] == INF) cout<<-1<<endl;
else cout<<dist[n];
return 0;
}
void dijkstra() {
int x = 0;
dist[1] = 0;
for(int j = 1; j <= n; j ++) {
x = 0;
// 找到未标记点中dist最小的
for(int i = 1; i <= n; i ++) {
if(vis[i] == 0 && (x == 0 || dist[i] < dist[x])) {
x = i;
}
}
vis[x] = 1;
// 用全局最小值点更新其他节点(我们已经找到一个最小的距离,看那条边与这个最小距离有联系,然后更新)
for(int i = 1; i <= n; i ++) {
dist[i] = min(dist[i],dist[x] + a[x][i]);
}
}
return ;
}
好的,谢谢你!