-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bellman-Ford.cpp
58 lines (54 loc) · 1.38 KB
/
Bellman-Ford.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
49
50
51
52
53
54
55
56
57
58
struct edge
{
int from, to, dist;
};
struct bellmanford
{
int n, m;
vector<edge> edges;
vector<int> g[maxn];
bool inq[maxn];
int d[maxn];
int p[maxn];
int cnt[maxn];
void init(int n)
{
this->n = n;
for(int i = 1; i <= n; ++i) g[i].clear();
edges.clear();
}
void addedge(int from, int to, double dist)
{
edges.push_back((edge){from, to, dist});
m = edges.size();
g[from].push_back(m - 1);
}
bool negativecycle()
{
queue<int> qu;
memset(inq, 0, sizeof(inq));
memset(cnt, 0, sizeof(cnt));
for(int i = 1; i <= n; ++i) { d[i] = 0; inq[i] = true; qu.push(i); }
d[1] = 0;
while(!qu.empty())
{
int u = qu.front(); qu.pop();
inq[u] = false;
for(int i = 0; i < g[u].size(); ++i)
{
edge & e = edges[g[u][i]];
if(d[e.to] > d[u] + e.dist)
{
d[e.to] = d[u] + e.dist;
p[e.to] = g[u][i];
if(!inq[e.to])
{
qu.push(e.to); inq[e.to] = true;
if(++cnt[e.to] >= n) return true;
}
}
}
}
return false;
}
}b;