fork download
  1. /*
  2.   Copyright 2011 Marek "p2004a" Rusinowski
  3.   Dijkstra algorithm
  4. */
  5. #include <cstdio>
  6. #include <algorithm>
  7. #include <vector>
  8. #include <set>
  9.  
  10. #define MAXN 1000000
  11. #define INF 0x7FFFFFF0
  12.  
  13. std::vector<std::pair<int, int> > edges[MAXN];
  14. int d[MAXN], n, m;
  15.  
  16. struct cmp {
  17. bool operator() (int a, int b) {
  18. if (d[a] < d[b]) return true;
  19. if (d[a] > d[b]) return false;
  20. return a < b;
  21. }
  22. };
  23.  
  24. void dijkstra(int v) {
  25. std::set<int, cmp> q;
  26. std::fill(d, d + n, INF);
  27. q.insert(v);
  28. d[v] = 0;
  29. while (!q.empty()) {
  30. int v = *(q.begin());
  31. q.erase(q.begin());
  32. for (unsigned i = 0; i < edges[v].size(); ++i) {
  33. if (d[v] + edges[v][i].second < d[edges[v][i].first]) {
  34. q.erase(edges[v][i].first);
  35. d[edges[v][i].first] = d[v] + edges[v][i].second;
  36. q.insert(edges[v][i].first);
  37. }
  38. }
  39. }
  40. }
  41.  
  42. int main() {
  43. int a, b, c;
  44. scanf("%d %d", &n, &m);
  45. for (int i = 0; i < m; ++i) {
  46. scanf("%d %d %d", &a, &b, &c);
  47. edges[--a].push_back(std::make_pair(--b, c));
  48. edges[b].push_back(std::make_pair(a, c));
  49. }
  50. dijkstra(0);
  51. for (int i = 0; i < n; ++i) {
  52. printf("%d ", d[i]);
  53. }
  54. printf("\n");
  55. return 0;
  56. }
  57.  
stdin
3 2
1 2 1
2 3 1
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:44: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
prog.cpp:46: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
stdout
0 1 2