3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib> 10 #include <string> 11 #include <set> 12 #include <stack> 13 #define LL long long 14 #define pii pair<int,int> 15 #define INF 0x3f3f3f3f 16 using namespace std; 17 const int maxn = 210; 18 int n,m,mp[maxn][maxn],d[maxn],s,t; 19 bool done[maxn]; 20 priority_queue< pii,vector< pii > ,greater< pii > >q; 21 void dijkstra(int s){ 22 while(!q.empty()) q.pop(); 23 int i,j,u,v; 24 for(i = 0; i < n; i++){ 25 done[i] = false; 26 d[i] = INF; 27 } 28 d[s] = 0; 29 q.push(make_pair(d[s],s)); 30 while(!q.empty()){ 31 u = q.top().second; 32 q.pop(); 33 if(done[u]) continue; 34 done[u] = true; 35 for(v = 0; v < n; v++){ 36 if(d[u] < INF && mp[u][v] < INF && d[v] > d[u]+mp[u][v]){ 37 d[v] = d[u]+mp[u][v]; 38 q.push(make_pair(d[v],v)); 39 } 40 } 41 if(done[t]) return; 42 } 43 } 44 int main() { 45 int i,j,u,v,w; 46 while(~scanf("%d %d",&n,&m)){ 47 for(i = 0; i < n; i++){ 48 for(j = 0; j < n; j++) 49 mp[i][j] = INF; 50 } 51 for(i = 0; i < m; i++){ 52 scanf("%d %d %d",&u,&v,&w); 53 if(mp[u][v] > w) mp[u][v] = mp[v][u] = w; 54 } 55 scanf("%d %d",&s,&t); 56 dijkstra(s); 57 printf("%d\n",d[t] == INF?-1:d[t]); 58 } 59 return 0; 60 }
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib> 10 #include <string> 11 #include <set> 12 #include <stack> 13 #define LL long long 14 #define INF 0x3f3f3f3f 15 using namespace std; 16 const int maxn = 210; 17 int n,m,s,t,d[maxn],mp[maxn][maxn]; 18 bool done[maxn]; 19 void spfa(int s){ 20 int i,j,u,v; 21 queue<int>q; 22 for(i = 0; i < n; i++) 23 d[i] = INF; 24 memset(done,false,sizeof(done)); 25 d[s] = 0; 26 q.push(s); 27 done[s] = true; 28 while(!q.empty()){ 29 u = q.front(); 30 q.pop(); 31 done[u] = false; 32 for(v = 0; v < n; v++){ 33 if(d[v] > d[u]+mp[u][v]){ 34 d[v] = d[u]+mp[u][v]; 35 if(!done[v]){ 36 done[v] = true; 37 q.push(v); 38 } 39 } 40 } 41 } 42 } 43 int main(){ 44 int i,j,u,v,w; 45 while(~scanf("%d %d",&n,&m)){ 46 for(i = 0; i < n; i++) 47 for(j = 0; j < n; j++) 48 mp[i][j] = INF; 49 for(i = 0; i < m; i++){ 50 scanf("%d %d %d",&u,&v,&w); 51 if(mp[u][v] > w) mp[u][v] = mp[v][u] = w; 52 } 53 scanf("%d %d",&s,&t); 54 spfa(s); 55 printf("%d\n",d[t] == INF?-1:d[t]); 56 } 57 return 0; 58 }