适用于单源最短路
边权重都是正数 稠密图(边数多)
O(N^2) //N是节点个数 M是边的数量
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define INF 0x3f3f3f3f
const int N = 510;
int Graph[N][N];
int Dis[N];
bool S[N];
int n;
int m;
void Dijkstra()
{
memset(Dis,INF,sizeof(Dis));
Dis[1] = 0;
for(int i = 0; i < n; i++)
{
int nShort = -1;
for(int j = 1; j <= n; j++)
{
if(!S[j] && (nShort == -1 || (Dis[nShort] > Dis[j]) ))
{
nShort = j;
}
}
S[nShort] = true;
for(int j = 1; j <= n; j++)
{
Dis[j] = min(Dis[j],Dis[nShort]+Graph[nShort][j]);
}
}
}
int main(int argc, char** argv)
{
memset(Graph,INF,sizeof(Graph));
scanf("%d%d",&n,&m);
while(m--)
{
int nStart;
int nEnd;
int nWeight;
scanf("%d%d%d",&nStart,&nEnd,&nWeight);
Graph[nStart][nEnd] = min(Graph[nStart][nEnd],nWeight);
}
Dijkstra();
for(int i = 1; i <= n; i++)
{
printf("%d ",Dis[i]);
}
return 0;
}