Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include <vector>
- using namespace std;
- struct rebro
- {
- int begin, end, ves;
- void new_rebro(int begin, int end, int ves)
- {
- this->begin = begin;
- this->end = end;
- this->ves = ves;
- }
- };
- class Graph
- {
- private:
- int n, **arr, shet_reber, *path;
- rebro *vse_rebra;
- public:
- Graph (int **matrix, int x, int shet)
- {
- n = x;
- arr = matrix;
- shet_reber = shet;
- vse_rebra = new rebro[shet_reber];
- spisok();
- }
- void spisok();
- void poisk_cycles();
- };
- void Graph::spisok()
- {
- int k = 0;
- for (int i = 0; i < n; i++)
- for (int j = 0; j < n; j++)
- if (arr[i][j] != 100000)
- {
- vse_rebra[k].new_rebro(i, j, arr[i][j]);
- k++;
- }
- }
- void Graph::poisk_cycles()
- {
- path = new int[n];
- int *d = new int[n];
- int x;
- for (int i = 0; i < n; i++)
- {
- path[i] = -1;
- d[i] = 0;
- }
- for (int i = 0; i < n; ++i)
- {
- x = -1;
- for (int j = 0; j < shet_reber; ++j)
- if (d[vse_rebra[j].begin] > d[vse_rebra[j].end] + vse_rebra[j].ves)
- {
- d[vse_rebra[j].begin] = max (-1000000, d[vse_rebra[j].end] + vse_rebra[j].ves);
- path[vse_rebra[j].begin] = vse_rebra[j].end;
- x = vse_rebra[j].begin;
- }
- }
- if (x == -1)
- cout << "NO";
- else
- {
- cout << "YES" << endl;
- vector<int> cycle;
- int y = x;
- for (int i = 0; i < n; ++i)
- y = path[y];
- for (int cur = x; ; cur = path[cur])
- {
- cycle.push_back (cur);
- if (cur == y && cycle.size() > 1)
- break;
- }
- cout << cycle.size() << endl;
- for (int i = 0; i < cycle.size(); ++i)
- cout << cycle[i]+1 << " ";
- }
- }
- int main()
- {
- int n, shet_reber = 0;
- cin >> n;
- int **arr = new int*[n];
- for ( int i = 0; i < n; i++)
- arr[i] = new int[n];
- for (int i = 0; i < n; i++)
- for (int j = 0; j < n; j++)
- {
- cin >> arr[i][j];
- if (arr[i][j] != 100000)
- shet_reber++;
- }
- Graph object(arr, n, shet_reber);
- object.poisk_cycles();
- }
- 6
- 0 -50 0 -34 0 0
- 0 0 -45 0 0 10
- -28 0 0 0 0 0
- 0 0 -31 0 25 0
- 48 0 0 0 0 60
- 20 0 0 0 0 0
Add Comment
Please, Sign In to add comment