标签:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 35831 | Accepted: 12172 |
Description
Input
Output
Sample Input
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
Sample Output
90
Hint
1 #include <iostream> 2 #include <vector> 3 #include <cstring> 4 #include <fstream> 5 #include <algorithm> 6 using namespace std; 7 const int INF=99999999; 8 int grap[1005][1005]; 9 int dist[1005]; 10 bool used[1005]; 11 int T,N; 12 13 void init() 14 { 15 for(int i=1; i<=N; i++) 16 for(int j=1; j<=N; j++) 17 { 18 if(i==j) 19 grap[i][j]=0; 20 else 21 grap[i][j]=INF; 22 } 23 } 24 25 int dijkstra() 26 { 27 fill(used,used + 1005,false); 28 for(int i=1; i<=N; i++) 29 dist[i] = INF; 30 dist[1] = 0; 31 32 for(int i = 2; i <= N; i++) 33 { 34 dist[i] = grap[1][i]; 35 } 36 37 for(int i = 1; i <= N; i++) 38 { 39 int min_c = INF,x; 40 for(int j = 1; j <= N; j++) 41 { 42 if(!used[j] && dist[j] < min_c) 43 { 44 min_c = dist[j]; 45 x = j; 46 } 47 } 48 used[x] = true; 49 for(int u = 1; u <= N; u++) 50 { 51 dist[u] = min(dist[u] , (dist[x] + grap[x][u]) ); 52 } 53 } 54 55 return dist[N]; 56 } 57 58 int main() 59 { 60 //freopen("in.txt","r",stdin); 61 while (cin >> T >> N) 62 { 63 init(); 64 65 for(int i = 0; i < T; i++) 66 { 67 int s,t,c; 68 cin >> s >> t >> c; 69 grap[t][s] = grap[s][t] = min(grap[s][t],c); 70 } 71 72 cout<<dijkstra()<<endl; 73 } 74 75 76 return 0; 77 }
堆优化
1 #include <iostream> 2 #include <vector> 3 #include <cstring> 4 #include <queue> 5 #include <fstream> 6 #include <algorithm> 7 using namespace std; 8 int T, N; 9 const int INF=99999999; 10 int cnt; 11 int lastshow[40010]; 12 int dist[40010]; 13 bool used[40010]; 14 typedef pair<int, int> P; 15 priority_queue<P, vector<P>, greater<P> > q; 16 17 18 struct edge{ 19 int to; 20 int wei; 21 int next; 22 }grap[40010]; 23 24 void insert(int a, int b, int c){ 25 cnt ++; 26 grap[cnt].to = b; 27 grap[cnt].next = lastshow[a]; 28 grap[cnt].wei = c; 29 lastshow[a] = cnt; 30 } 31 32 33 void dijkstra(){ 34 memset(used, 0, sizeof(used)); 35 q.push(make_pair(dist[1], 1)); 36 while(!q.empty()){ 37 P u = q.top(); 38 q.pop(); 39 int x = u.second; 40 if(used[x]) 41 continue; 42 used[x] = true; 43 for(int i = lastshow[x]; i != -1; i = grap[i].next){ 44 if(dist[grap[i].to] > dist[x] + grap[i].wei){ 45 dist[grap[i].to] = dist[x] + grap[i].wei; 46 q.push(make_pair(dist[grap[i].to], grap[i].to)); 47 } 48 } 49 } 50 } 51 52 53 54 int main() 55 { 56 //freopen("in.txt","r",stdin); 57 while (cin >> T >> N) 58 { 59 cnt = 0; 60 memset(lastshow, -1, sizeof(lastshow)); 61 for(int i = 1; i <= N; i ++) 62 dist[i] = (i == 1 ? 0 : INF); 63 for(int i = 0; i < T; i ++) 64 { 65 int a, b, c; 66 cin >> a >> b >> c; 67 insert(a, b, c); 68 insert(b, a, c); 69 } 70 71 dijkstra(); 72 cout<<dist[N]<<endl; 73 } 74 75 76 return 0; 77 }
标签:
原文地址:http://www.cnblogs.com/cjshuang/p/4734578.html