CSES - Cycle Finding, my algorithm finds cycle if it has any negative weight, but it is not accepted by CSES

795 Views Asked by At

https://cses.fi/problemset/task/1197 Cycle Finding, my algorithm prints cycle if it has any negative weight, but jury is not accepting.

they suggested to use bellman ford algorithm but my dfs also working fine.

Question: You are given a directed graph, and your task is to find out if it contains a negative cycle, and also give an example of such a cycle.

Input

The first input line has two integers n and m: the number of nodes and edges. The nodes are numbered 1,2,…,n.

After this, the input has m lines describing the edges. Each line has three integers a, b, and c: there is an edge from node a to node b whose length is c.

Output

If the graph contains a negative cycle, print first "YES", and then the nodes in the cycle in their correct order. If there are several negative cycles, you can print any of them. If there are no negative cycles, print "NO".

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define f first
#define s second
#define pb push_back
typedef pair<ll, ll> pll;
ll n, m;
const int nxm = 2.5e3 + 5;
vector<pll> adj[nxm];
bool visi[nxm];
pll parent[nxm];
void dfs(int u)
{
    visi[u] = true;
    // cout<<u<<" ";
    for (pll v : adj[u])
    {
        if (visi[v.s])
        {
            // cout<<v.s;
            int u1 = u;
            // flag is for checking if the cycle has any negative weight or not
            bool flag = false;
            if (v.f < 0)
                flag = true;
            vector<int> res;
            res.pb(v.s);
            while (u1!=0 && u1 ^ v.s)
            {
                res.pb(u1);
                u1 = parent[u1].s;
                if (parent[u1].f < 0)
                    flag = true;
            }
            res.pb(v.s);
            if (flag)
            {
                reverse(res.begin(),res.end());
                cout << "YES" << endl;
                for (int x : res)
                    cout << x << " ";
                exit(0);
            }
        }
        else
        {
            parent[v.second] = {v.f, u};
            dfs(v.s);
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        ll a, b, c;
        cin >> a >> b >> c;
        adj[a].pb({c, b});
    }
    memset(visi, 0, sizeof(visi));
    for (int i = 1; i <= n; i++)
    {
        if(visi[i])
            continue;
        parent[i] = {0, 0};
        dfs(i);
    }
    cout << "NO";
    return 0;
}

Sample test case:

5 10
1 3 1000
2 4 1000
3 5 1000
4 1 1000
5 2 1000
1 2 -2
2 3 -2
3 4 -2
4 5 -2
5 1 -2

Jury's answer

YES
2 3 4 5 1 2 

My answer

YES
5 2 4 5 
0

There are 0 best solutions below