Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- struct Edge{
- int from, to;
- ll weight;
- };
- int t;
- int n, m;
- vector<Edge> graph;
- int parent[5001];
- bool visited[5001];
- void print(int v){
- //cout << "HI" << '\n';
- while(!visited[v]){
- //#1. Find first value to actually begin cycle
- visited[v] = true;
- v = parent[v];
- }
- vector<int> ans;
- int temp = parent[v];
- ans.push_back(v);
- //cout << " v: " << v << '\n';
- //int count = 1;
- while(temp != v){
- //count++;
- //if(count>20) break;
- //cout << "temp: " << temp << '\n';
- ans.push_back(temp);
- temp = parent[temp];
- }
- ans.push_back(v);
- reverse(ans.begin(), ans.end());
- for(auto a: ans){
- cout << " " << a;
- }
- cout << '\n';
- //cout << ans[0] << '\n';
- }
- bool isNegative(){
- vector<ll> dist;
- dist.resize(n+1, 0);
- dist[1] = 0;
- bool check = false;
- for(int i=1; i<=n; i++){
- //cout << "i: " << i << '\n';
- check = false;
- for(Edge e: graph){
- //if(dist[e.from] != INT_MAX){
- //cout << "e.to: " << e.to << ", e.from: " << e.from << ", e.weight: " << e.weight << '\n';
- if(dist[e.to]>dist[e.from]+e.weight){
- dist[e.to] = dist[e.from]+e.weight;
- //cout << "i: " << i << ", dist[e.to]: " << dist[e.to] << ", dist[e.from]: " << dist[e.from] << '\n';
- parent[e.to] = e.from;
- check = true;
- if(i==n){
- cout << "YES";
- print(e.to);
- //#1. need to use value that is actually part of cycle or else infinite loop on some cases
- return true;
- }
- //cout << "HI" << '\n';
- }
- //}
- }
- if(!check) break;
- }
- return false;
- }
- int main(){
- //freopen("cyclefind.in", "r", stdin);
- cin >> n >> m;
- graph.clear();
- graph.resize(m);
- //dist.resize(n+1, INT_MAX);
- for(int i=0; i<m; i++){
- cin >> graph[i].from >> graph[i].to >> graph[i].weight;
- //cout << graph[i].from << ", " << graph[i].to << ", " << graph[i].weight << '\n';
- }
- if(isNegative()){
- //cout << "YES" << '\n';
- }else{
- cout << "NO" << '\n';
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement