forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SPFA.cpp
48 lines (40 loc) · 705 Bytes
/
SPFA.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
44
45
46
47
48
const int INF=1e9;
int n, m;
int dist[N], cnt[N];
bool inqueue[N];
vector<pair<int, int> > g[N];
bool SPFA(int source) //Returns true if there is a negative cycle reachable from source
{
queue<int> q;
for(int i=1;i<=n;i++)
{
cnt[i]=0;
dist[i]=INF;
}
dist[source]=0;
q.push(source);
inqueue[source]=true;
while(!q.empty())
{
int v=q.front();
q.pop();
inqueue[v]=false;
for(auto &edge:g[v])
{
int to=edge.first;
int w=edge.second;
if(dist[v] + w < dist[to])
{
dist[to] = dist[v] + w;
dist[to] = max(dist[to], -INF);
if(!inqueue[to])
{
q.push(to);
inqueue[to]=true;
cnt[to]++;
if(cnt[to]>n)
return true;
}
}
}
}