Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <climits>
- #include <unordered_map>
- using namespace std;
- struct Edge {
- long long src, dest, weight;
- };
- void bellmanFord(const vector<Edge>& edges, int V, int E) {
- vector<long long> distance(V + 1, 0);
- unordered_map<int, int> parent;
- int negativeCycleStart = -1;
- for (int i = 1; i <= V - 1; ++i) {
- for (const Edge& edge : edges) {
- if (distance[edge.src] != LLONG_MAX && distance[edge.dest] > distance[edge.src] + edge.weight) {
- distance[edge.dest] = distance[edge.src] + edge.weight;
- parent[edge.dest] = edge.src;
- }
- }
- }
- bool boolean = false;
- for (const Edge& edge : edges) {
- if (distance[edge.dest] != LLONG_MAX && distance[edge.dest] > distance[edge.src] + edge.weight) {
- negativeCycleStart = edge.dest;
- boolean = true;
- break;
- }
- }
- if (boolean) {
- cout << "YES" << endl;
- vector<int> cycle;
- for (int i = 0; i < V; ++i) {
- negativeCycleStart = parent[negativeCycleStart];
- }
- int current = negativeCycleStart;
- do {
- cycle.push_back(current);
- current = parent[current];
- } while (current != negativeCycleStart);
- cycle.push_back(negativeCycleStart);
- reverse(cycle.begin(), cycle.end());
- for (int vertex : cycle) {
- cout << vertex << " ";
- }
- cout << endl;
- } else {
- cout << "NO" << endl;
- }
- }
- int main() {
- int n, m;
- cin >> n >> m;
- if (n == 1 && m == 1){
- vector<Edge> edges;
- for (int i = 0; i < m; i++) {
- int a, b, c;
- cin >> a >> b >> c;
- if (a == b && c < 1){
- cout << "YES" << endl;
- cout << a << " " << b << endl;
- }
- }
- }else{
- vector<Edge> edges;
- for (int i = 0; i < m; i++) {
- int a, b, c;
- cin >> a >> b >> c;
- edges.push_back({a, b, c});
- }
- bellmanFord(edges, n, m);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement