邻接表法
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 510, M = 100010;
int h[N],e[M],ne[M],w[M],idx;
int dist[N];
bool st[N];
int n,m;
void add(int a,int b,int c)
{
e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++;
}
int dijkstra()
{
memset(dist,0x3f,sizeof dist);
dist[1]=0;
for (int i=1;i<=n;i++)
{
int t=-1;
for (int j=1;j<=n;j++)
{
if (!st[j]&&(t==-1||dist[t]>dist[j]))
t=j;
}
st[t]=true;
for (int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
dist[j]=min(dist[j],dist[t]+w[i]);
}
}
if (dist[n]==0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
memset(h,-1,sizeof h);
scanf("%d%d",&n,&m);
while (m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
int ans=dijkstra();
printf("%d\n",ans);
return 0;
}
邻接矩阵版本
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510;
int dist[N];
int g[N][N];
bool st[N];
int n,m;
int dijkstra()
{
memset(dist,0x3f,sizeof dist);
dist[1]=0;
for (int i=0;i<n;i++)
{
int t=-1;
for (int j=1;j<=n;j++)
{
if (!st[j]&&(t==-1||dist[t]>dist[j]))
t=j;
}
st[t]=true;
for (int j=1;j<=n;j++)
dist[j]=min(dist[j],dist[t]+g[t][j]);
}
if (dist[n]==0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
scanf("%d%d",&n,&m);
memset(g,0x3f,sizeof g);
while (m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
g[a][b]=min(g[a][b],c);
}
int ans=dijkstra();
printf("%d\n",ans);
return 0;
}