SPFA算法
- 对Bellman-Ford算法进行了优化。
- 用宽搜进行优化。
题目
与上篇博客题目类似,数据范围有所不同。
数据范围
1 1 1 ≤ \le ≤ n , m n, m n,m ≤ \le ≤ 1 0 5 10^5 105
图中涉及边长绝对值不超过10000.
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1000010;
int n, m;
int h[N], w[N], e[N], ne[N];
int dist[N];
bool st[N];
int idx;
typedef pair<int, int> PII;
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
int spfa() {
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
queue<int> q;
q.push(1);
st[1] = true;
while (q.size()) {
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
if (!st[j]) {
q.push(j);
st[j] = true;
}
}
}
}
return dist[n];
}
int main() {
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m --) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
int res = spfa();
if (res == 0x3f3f3f3f)
puts("impossible");
else printf("%d\n", res);
return 0;
}
判断是否有负环
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1000010;
int n, m;
int h[N], w[N], e[N], ne[N];
int dist[N], cnt[N];
bool st[N];
int idx;
typedef pair<int, int> PII;
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
bool spfa() {
// 需要把所有点都放进去
queue<int> q;
for (int i = 1; i <= n; i ++) {
st[i] = true;
q.push(i);
}
while (q.size()) {
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true;
if (!st[j]) {
q.push(j);
st[j] = true;
}
}
}
}
return false;
}
int main() {
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m --) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
if (spfa())
puts("Yes");
else
puts("No");
return 0;
}