chillurbrain

12.2.3. Цикл

May 26th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. struct edge
  7. {
  8.     int from, to, cost;
  9. };
  10. const int INF = 1e9;;
  11.  
  12. int main(){
  13.     int n;
  14.     cin >> n;
  15.     vector <edge> E;
  16.     for (int i = 0; i < n; i++)
  17.     {
  18.         for (int j = 0; j < n; j++)
  19.         {
  20.             int x;
  21.             cin >> x;
  22.             if (x != 0 && x != 100000){
  23.                 E.push_back({ i, j, x });
  24.             }
  25.         }
  26.     }
  27.     int x;
  28.     vector<int> d(n, INF), p(n, -1);
  29.     d[0] = 0;
  30.     for (int i = 0; i < n; i++)
  31.     {
  32.         x = -1;
  33.         for (int j = 0; j < E.size(); j++)
  34.         {
  35.             int from = E[j].from;
  36.             int to = E[j].to;
  37.             int cost = E[j].cost;
  38.             if (d[to] > d[from] + cost)
  39.             {
  40.                 d[to] = max(d[from] + cost, -INF);
  41.                 p[to] = from;
  42.                 x = to;
  43.             }
  44.         }
  45.     }
  46.     if (x == -1)
  47.     {
  48.         cout << "NO" << endl;
  49.     }
  50.     else{
  51.         int y = x;
  52.         for (int i = 0; i < n; i++)
  53.         {
  54.             y = p[y];
  55.         }
  56.         vector <int> path;
  57.         for (int cur = y;; cur = p[cur])
  58.         {
  59.             path.push_back(cur);
  60.             if (cur == y && path.size() > 1)
  61.             {
  62.                 break;
  63.             }
  64.         }
  65.         reverse(path.begin(), path.end());
  66.         cout << "YES" << endl;
  67.         cout << path.size() << endl;
  68.         for (int i = 0; i < path.size(); i++)
  69.         {
  70.             cout << path[i] + 1;
  71.             if (i != path.size() - 1)
  72.             {
  73.                 cout << ' ';
  74.             }
  75.         }
  76.         cout << endl;
  77.     }
  78.     system("pause");
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment