Advertisement
Dang_Quan_10_Tin

negcy_But Stupid

Oct 14th, 2020
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <stack>
  4. #include <bitset>
  5. #include <algorithm>
  6. #include <vector>
  7. #define task ""
  8.  
  9. using namespace std;
  10. using ll = long long;
  11. using ld = long double;
  12.  
  13. const int N = 5e3 + 2;
  14. int n, m;
  15. const ll Inf = 1e18;
  16. ll w[N], d[N];
  17. vector<pair<int, int>> adj[N];
  18. stack<int> ans;
  19.  
  20. void Read()
  21. {
  22.     cin >> n >> m;
  23.     for (int i = 1; i <= m; ++i)
  24.     {
  25.         int u, v;
  26.         cin >> u >> v >> w[i];
  27.         adj[u].push_back({v, i});
  28.         //adj[v].push_back({u, i});
  29.     }
  30. }
  31.  
  32. bool dfs(int v, const int &goals)
  33. {
  34.     if (d[v] < 0 && v == goals)
  35.     {
  36.         cout << "YES\n";
  37.         ans.push(v);
  38.         return true;
  39.     }
  40.     for (auto i : adj[v])
  41.         if (d[i.first] > d[v] + w[i.second])
  42.         {
  43.             d[i.first] = d[v] + w[i.second];
  44.             if (d[i.first] <= 0 && dfs(i.first, goals))
  45.             {
  46.                 ans.push(v);
  47.                 return true;
  48.             }
  49.         }
  50.     return false;
  51. }
  52.  
  53. void Solve()
  54. {
  55.     for (int i = 1; i <= n; ++i)
  56.     {
  57.         fill_n(d, N, Inf);
  58.         d[i] = 0;
  59.         if (dfs(i, i))
  60.         {
  61.             while (!ans.empty())
  62.             {
  63.                 cout << ans.top() << " ";
  64.                 ans.pop();
  65.             }
  66.             return;
  67.         }
  68.     }
  69.     cout << "NO";
  70. }
  71.  
  72. int32_t main()
  73. {
  74.     ios_base::sync_with_stdio(0);
  75.     cin.tie(0);
  76.     cout.tie(0);
  77.     if (fopen(task ".INP", "r"))
  78.     {
  79.         freopen(task ".INP", "r", stdin);
  80.         freopen(task ".OUT", "w", stdout);
  81.     }
  82.     Read();
  83.     Solve();
  84. }
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement