dij朴素算法总结
原题链接:https://www.acwing.com/problem/content/851/

#include<iostream> #include<algorithm> #include<cstring> using namespace std; const int maxn = 510,INF = 0x3f3f3f3f; int g[maxn][maxn]; int dist[maxn]; bool st[maxn]; int n,m; int dij(){ 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; /* ----------找到集合外距离最小点t----------*/ 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(){ cin>>n>>m; //初始化图 for(int i = 0;i<=n;i++){ for(int j = 0;j<=n;j++){ if(i==j)g[i][j] = 0; else g[i][j] = INF; } } //处理重边 while(m--){ int a,b,c; cin>>a>>b>>c; g[a][b] = min(g[a][b],c); } int t = dij(); if(t==-1)cout<<-1<<endl; else cout<<t<<endl; return 0; }

浙公网安备 33010602011771号