3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
/*#include <stdio.h> #include <string.h> #define MAX_N 205 #define INF 0x3f3f3f3f int dist[MAX_N][MAX_N]; int n, m, begin, end; void add_edge(int a,int b,int c) { dist[a][b] = dist[b][a] = (c>dist[a][b]?dist[a][b]:c); } void Ford() { int i,j,k; for(k=0;k<n;k++) { for(i=0;i<n;i++) { for(j=0;j<n;j++) { dist[i][j] = dist[i][j] > dist[i][k] + dist[k][j] ? dist[i][k]+dist[k][j] : dist[i][j]; } } } } void _print() { if(dist[begin][end]==INF) { printf("-1\n"); } else { printf("%d\n",dist[begin][end]); } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { int a,b,c; int i,j; for( i=0;i<n;++i ) { for( j=0;j<i;++j ) { if(i==j) { dist[i][j]=0; } else { dist[i][j]=dist[j][i]=INF; } } } for(i=0;i<m;i++) { scanf("%d%d%d",&a,&b,&c); add_edge(a,b,c); } scanf("%d%d",&begin,&end); Ford(); _print(); } return 0; }*/ #include <stdio.h> #include <string.h> #define MAX_N 205 #define INF 0x3f3f3f3f int g[MAX_N][MAX_N]; int dist[MAX_N]; int used[MAX_N]; int n, m, begin, end; void add_edge(int a,int b,int c) { g[a][b] = g[b][a] = (c>g[a][b]?g[a][b]:c); } void init() { memset(dist,0x3f3f3f,sizeof(dist)); memset(used,0,sizeof(used)); } void Dijkstra() { init(); dist[begin] = 0; while(1) { int min = INF; int u = -1,v,i; for(i=0;i<n;i++) { if(min>dist[i] && !used[i]) { min = dist[i]; u = i; } } used[u] = 1; if(u==-1) { break; } for(v=0;v<n;v++) { if(g[u][v]!=INF && dist[v]>dist[u]+g[u][v]) { dist[v] = dist[u] + g[u][v] > dist[v] ? dist[v]: dist[u]+g[u][v]; } } } } void _print() { if(dist[end]==INF) { printf("-1\n"); } else { printf("%d\n",dist[end]); } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { int a,b,c; int i,j; memset(g,INF,sizeof(g)); for(i=0;i<m;i++) { scanf("%d%d%d",&a,&b,&c); add_edge(a,b,c); } scanf("%d%d",&begin,&end); Dijkstra(); _print(); } return 0; }