fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define endl "\n"
  4. #define int long long
  5. #define faster() ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
  6.  
  7. typedef pair<int,int> ii ;
  8.  
  9. int n , m , s ;
  10. vector<ii> ke[200005];
  11. bool visited[200005];
  12. struct Edge{
  13. int u , v , w ;
  14. };
  15. vector<Edge> dsCanh ;
  16.  
  17.  
  18. void BellmanFord(int s){
  19. vector<int> d(n + 1 , 1e9);
  20. d[s] = 0 ;
  21. for(int i = 1 ; i <= n - 1 ; i++){
  22. for(Edge e : dsCanh){
  23. int u = e.u ;
  24. int v = e.v ;
  25. int w = e.w ;
  26. if(d[u] < 1e9){
  27. d[v] = min(d[v] , d[u] + w);
  28. }
  29. }
  30. }
  31.  
  32. for(int i = 1 ; i <= n ; i++){
  33. cout << d[i] << " ";
  34. }
  35. }
  36.  
  37. void solve(){
  38. cin >> n >> m >> s ;
  39. for(int i = 1 ; i <= m ; i++){
  40. int x , y, w ; cin >> x >> y >> w ;
  41. ke[x].push_back({y , w});
  42. ke[y].push_back({x , w});
  43. // them ca 2 canh vao dsCanh
  44. dsCanh.push_back({x , y, w});
  45. dsCanh.push_back({y , x, w});
  46. }
  47. BellmanFord(s);
  48. }
  49.  
  50. signed main() {
  51. faster();
  52. int test = 1 ;
  53. // cin >> test ;
  54. while(test--) solve();
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0.01s 8180KB
stdin
10 44 5
7 5 60
9 8 31
9 1 83
4 3 25
6 2 1
4 1 52
6 3 76
7 6 95
9 7 84
8 2 91
10 7 8
6 4 32
10 2 76
3 1 62
10 6 88
8 3 12
5 3 15
5 4 40
9 2 20
3 2 5
5 1 36
9 4 98
8 6 65
8 5 95
10 3 55
9 6 95
10 1 5
4 2 70
7 1 80
10 4 35
7 2 99
10 9 24
6 5 94
2 1 77
8 1 12
8 4 76
9 3 27
5 2 5
9 5 12
10 5 1
8 7 59
6 1 1
10 8 92
7 3 54
stdout
6 5 10 35 0 6 9 18 12 1