题目描述:
给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。
1 <= n <= 20000,1 <= m <= 200000,-10000 <= len <= 10000,保证从任意顶点都能到达其他所有顶点。
SPFA:
- 边权存在负数时不能用Dijkstra。
- 判断负圈:如果一个点进队列超过 n 次,则说明图中存在负圈 (代码中neg数组)。
注意:
- 如果是双向边的话链式前向星需要开两倍空间。
- 还要注意边的数量,不能想当然为 N 。
AC Codes:
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
//#include <unordered_set>
//#include <unordered_map>
#include <deque>
#include <list>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
//#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
//cout << fixed << setprecision(2);
//cout << setw(2);
const int N = 2e4 + 6, M = 2e5 + 5, INF = 0x3f3f3f3f;
int n, m;
int dis[N], inq[N], neg[N];
int head[N], Next[M], ver[M], edge[M], tot;
void add(int u, int v, int w) {
ver[++tot] = v, edge[tot] = w;
Next[tot] = head[u], head[u] = tot;
}
bool SPFA() {
queue<int> q;
memset(dis, 0x3f, sizeof(dis));
q.push(1);
neg[1] = inq[1] = 1, dis[1] = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
inq[x] = 0;
for (int i = head[x]; i; i = Next[i]) {
int y = ver[i], w = edge[i];
if (dis[x] + w < dis[y]) {
dis[y] = dis[x] + w;
if (!inq[y]) {
q.push(y);
inq[y] = 1;
neg[y]++;
if (neg[y] > n) return true;
}
}
}
}
return false;
}
int main() {
//freopen("/Users/xumingfei/Desktop/ACM/test.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> m;
tot = 1;
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
add(x, y, z);
}
SPFA();
for (int i = 2; i <= n; i++) cout << dis[i] << '\n';
return 0;
}