forked from DHEERAJHARODE/Hacktoberfest2024-Open-source-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnegativeCycleFinding.cpp
43 lines (38 loc) · 866 Bytes
/
negativeCycleFinding.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
struct Edge {
ll a, b, cost;
};
int n, m;
vector<Edge> edges;
const ll INF = 1e9 + 5;
void solve(){
vector<ll> d(n);
vector<int> p(n, -1);
int x;
for (int i = 0; i < n; ++i) {
x = -1;
for (Edge e : edges) {
if (d[e.a] + e.cost < d[e.b]) {
d[e.b] = d[e.a] + e.cost;
p[e.b] = e.a;
x = e.b;
}
}
}
if (x == -1) {
cout << "NO\n";
} else {
for (int i = 0; i < n; ++i)
x = p[x];
vector<int> cycle;
for (int v = x;; v = p[v]) {
cycle.push_back(v);
if (v == x && cycle.size() > 1)
break;
}
reverse(cycle.begin(), cycle.end());
cout << "YES\n";
for (int v : cycle)
cout << v+1 << ' ';
cout << endl;
}
}