标签:
Input
Output
Sample Input
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
Sample Output
90
O(n^2)
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #include <vector> 6 #include <queue> 7 #include <set> 8 #include <map> 9 #include <string> 10 #include <cmath> 11 #include <stdlib.h> 12 #define MAXSIZE 1005 13 using namespace std; 14 15 int t,n; 16 int m[MAXSIZE][MAXSIZE],dis[MAXSIZE],vis[MAXSIZE]; 17 18 void dij(int s) 19 { 20 int i,j,k; 21 for(i = 0;i<n;i++) 22 { 23 dis[i] = m[s][i]; 24 vis[i] = 0; 25 } 26 dis[s] = 0; 27 vis[s] = 1; 28 for(i = 1;i<=n;i++) 29 { 30 k = 0; 31 int mn = 1000000; 32 for(j = 1;j<=n;j++) 33 if(!vis[j]&&dis[j]<mn) 34 { 35 mn = dis[j]; 36 k = j; 37 } 38 vis[k] = 1; 39 for(j = 1;j<=n;j++) 40 if(!vis[j]&&dis[j]>dis[k]+m[k][j]) 41 dis[j] = dis[k]+m[k][j]; 42 } 43 } 44 45 int main() 46 { 47 freopen("caicai.txt","r",stdin); 48 cin>>t>>n; 49 int i,j,a,b,w; 50 for(i = 0;i<=n;i++) 51 for(j = 0;j<=n;j++) 52 m[i][j] = 1000; 53 for(i = 0;i<t;i++) 54 { 55 scanf("%d%d%d",&a,&b,&w); 56 if(m[a][b]>w) 57 { 58 m[a][b] = w; 59 m[b][a] = w; 60 } 61 } 62 dij(n); 63 cout<<dis[1]<<endl; 64 return 0; 65 }
标签:
原文地址:http://www.cnblogs.com/caitian/p/5835806.html