Korotkodul

форд бэлман отрицательный цикл_OK

Feb 28th, 2022 (edited)
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <string>
  7. #include <stack>
  8. #include <set>
  9. #include <map>
  10. #define pii pair <int,int>
  11. #define vec vector
  12. using namespace std;
  13. using ll = long long;
  14. using ld = long double;
  15. using db = double;
  16. void cv(vector <int> &v){
  17. for (auto x: v) cout<<x<<' ';
  18. cout<<"\n";
  19. }
  20.  
  21. void cvl(vector <ll> &v){
  22. for (auto x: v) cout<<x<<' ';
  23. cout<<"\n";
  24. }
  25.  
  26.  
  27. void cvv(vector <vector <int> > &v){
  28. for (auto x: v) cv(x);
  29. cout<<"\n";
  30. }
  31.  
  32. void cvb(vector <bool> v){
  33. for (bool x: v) cout<<x<<' ';
  34. cout<<"\n";
  35. }
  36.  
  37. void cvs(vector <string> v){
  38. for (auto a: v){
  39. cout<<a<<"\n";
  40. }
  41. }
  42.  
  43.  
  44.  
  45.  
  46. struct ed{
  47. int fr, to, w;
  48. };
  49.  
  50. int inf = 2e9;
  51.  
  52. int main()
  53. {
  54. ios::sync_with_stdio(0);
  55. cin.tie(0);
  56. cout.tie(0);
  57. int n; cin>>n;
  58. int m = 0;
  59. vector <int> d(n, 0);
  60. vector <ed> G;
  61. vector <int> pred(n);
  62. for (int i = 0; i < n ;++i){
  63. for (int j = 0; j < n;++j){
  64. int ds; cin>>ds;
  65. if (ds == 100000) continue;
  66. ed x = {i, j, ds};
  67. m++;
  68. G.push_back(x);
  69. }
  70. }
  71. for (ed x: G){
  72. // cout<<x.fr<<' '<<x.to<<' '<<x.w<<"\n";
  73. }
  74. //cout<<"m = "<<m<<"\n";
  75. for (int i = 0; i < n; ++i){
  76. for (int j = 0; j < m; ++j){
  77. ed x = G[j];
  78. if (d[x.fr] == inf) continue;
  79. if (d[x.to] > d[x.fr] + x.w){
  80. d[x.to] = d[x.fr] + x.w;
  81. pred[x.to] = x.fr;
  82. }
  83. }
  84. }
  85.  
  86. vector <bool> upd(n, 0);
  87. for (int j = 0; j < m; ++j){
  88. ed x = G[j];
  89. if (d[x.fr] == inf) continue;
  90. if (d[x.to] > d[x.fr] + x.w){
  91. upd[x.to] = 1;
  92. d[x.to] = d[x.fr] + x.w;
  93. pred[x.to] = x.fr;
  94. }
  95. }
  96. for (int i = 0; i < n;++i){
  97. if (upd[i]){
  98. int v = i;
  99. for (int j = 0; j < n+1;++j){
  100. v = pred[v];
  101. }
  102. int str = v;
  103. vector <int> ans = {str};
  104. v = pred[v];
  105. while (v != str){
  106. ans.push_back(v);
  107. v = pred[v];
  108. }
  109. reverse(ans.begin() , ans.end());
  110. ans.push_back(ans[0]);
  111. cout<<"YES\n";
  112. cout<<ans.size()<<"\n";
  113. for (int v: ans) cout<<v+1<<' ';
  114. exit(0);
  115. }
  116. }
  117. cout<<"NO\n";
  118. }
  119.  
Add Comment
Please, Sign In to add comment