Dijkstra模板题,也可以用Floyd算法。
关于Dijkstra算法有两种写法,只有一点细节不同,思想是一样的。
写法1:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #define Mod 1000000007 using namespace std; #define N 1007 int mp[N][N],n,m; int dis[N],vis[N]; void Dijastra(int s) { int now = s; int i,k; dis[now] = 0; vis[now] = 1; for(i=1;i<=n;i++) { for(k=1;k<=n;k++) //order 1 { if(mp[now][k] != Mod && dis[now] + mp[now][k] < dis[k]) dis[k] = dis[now] + mp[now][k]; } int mini = Mod; //order 2 for(k=1;k<=n;k++) { if(dis[k] < mini && !vis[k]) { now = k; mini = dis[k]; } } vis[now] = 1; } } int main() { int u,v,w,i,j; while(scanf("%d%d",&m,&n)!=EOF) { for(i=1;i<=n;i++) dis[i] = Mod; dis[1] = 0; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) mp[i][j] = Mod; mp[i][i] = 0; } while(m--) { scanf("%d%d%d",&u,&v,&w); if(w < mp[u][v]) mp[u][v] = mp[v][u] = w; } memset(vis,0,sizeof(vis)); Dijastra(1); printf("%d ",dis[n]); } return 0; }
写法2:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #define Mod 1000000007 using namespace std; #define N 1007 int mp[N][N],n,m; int dis[N],vis[N]; void Dijastra(int s) { int now; int i,k; dis[s] = 0; for(i=1;i<=n;i++) { int mini = Mod; //order 1 for(k=1;k<=n;k++) { if(dis[k] < mini && !vis[k]) { now = k; mini = dis[k]; } } vis[now] = 1; for(k=1;k<=n;k++) //order 2 { if(mp[now][k] != Mod && dis[now] + mp[now][k] < dis[k]) dis[k] = dis[now] + mp[now][k]; } } } int main() { int u,v,w,i,j; while(scanf("%d%d",&m,&n)!=EOF) { for(i=1;i<=n;i++) dis[i] = Mod; dis[1] = 0; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) mp[i][j] = Mod; mp[i][i] = 0; } while(m--) { scanf("%d%d%d",&u,&v,&w); if(w < mp[u][v]) mp[u][v] = mp[v][u] = w; } memset(vis,0,sizeof(vis)); Dijastra(1); printf("%d ",dis[n]); } return 0; }