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