洛谷 P5960 【模板】差分约束算法

D e s c r i p t i o n Description Description

洛谷 P5960 【模板】差分约束算法_第1张图片

S o l u t i o n Solution Solution

S P F A : SPFA: SPFA:

对于每个 X i − X j ≤ Y X_i - X_j\leq Y XiXjY,建一条边 ( j , i ) = Y (j, i) = Y (j,i)=Y
然后要有一个超级源点 0 0 0,对于 i ∈ [ 1 , n ] i∈[1,n] i[1,n]建一条边 ( 0 , i ) = 0 (0,i)=0 (0,i)=0
跑一遍最短路/最长路
最短路可以求出 x ≤ 0 x\leq 0 x0的最大解
最长路可以求出 x ≥ 0 x\geq 0 x0的最小解
如果在求最短路时有负环则无解
在求最长路时有正环则无解
判断正负环就判断一个点入队次数,若 ≥ n \geq n n则无解 ( ( (最短路最多有 n − 1 n-1 n1条边 ) ) )

B e l l m a n − F o r d : Bellman-Ford: BellmanFord:

不需要超级源点
然后跑一遍最短路/最长路
然后 O ( m ) O(m) O(m)查询能不能再松弛
如果可以就是无解

A c c e p t e d   c o d e Accepted\ code Accepted code

S P F A : SPFA: SPFA:
#include
#include
#include

using namespace std;

const int inf = 1e9;

struct Line {
	int to, w, next;
}e[10005];//记得算上超级源点连着的n条边

int n, m, cnt;
int dis[5005], sum[5005], last[5005];
bool v[5005];

inline void add(int x, int y, int w) {
	e[++cnt] = (Line){y, w, last[x]}; last[x] = cnt;
}

bool spfa() {
	queue <int> q;
	q.push(0), v[0] = 1, sum[0] = 1, dis[0] = 0;
	while (q.size()) {
		int x = q.front(); q.pop(); v[x] = 0;
		for (int i = last[x]; i; i = e[i].next) {
			int y = e[i].to;
			if (dis[y] > dis[x] + e[i].w) {
				dis[y] = dis[x] + e[i].w;
				if (!v[y]) v[y] = 1, ++sum[y], q.push(y);
				if (sum[y] >= n) return 1; //判断负环
			}
		}
	}
	return 0;
}

int main() {
	scanf("%d %d", &n, &m);
	for (int x, y, w, i = 1; i <= m; ++i)
		scanf("%d %d %d", &x, &y, &w), add(y, x, w);
	for (int i = 1; i <= n; ++i) add(0, i, 0);
	for (int i = 1; i <= n; ++i) dis[i] = inf;
	if (spfa()) return !puts("NO");
	for (int i = 1; i <= n; ++i)
		printf("%d\n", dis[i]);
} 
B e l l m a n − F o r d Bellman-Ford BellmanFord
#include
#include

using namespace std;

const int inf = 1e9;

struct Line {
	int from, to, w;
}e[5005];

int n, m;
int dis[5005];

int main() {
	scanf("%d %d", &n, &m);
	for (int x, y, w, i = 1; i <= m; ++i)
		scanf("%d %d %d", &x, &y, &w), e[i] = (Line){y, x, w};
	for (int i = 2; i <= n; ++i) dis[i] = inf;
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			dis[e[j].to] = min(dis[e[j].from] + e[j].w, dis[e[j].to]);
	for (int i = 1; i <= m; ++i)
		if (dis[e[i].from] + e[i].w < dis[e[i].to])//判断是否能再松弛,如果可以则无解
			return !puts("NO");
	for (int i = 1; i <= n; ++i)
		printf("%d\n", dis[i]);
} 

你可能感兴趣的:(差分约束,最短路,bellman–ford,algorithm,SPFA,最短路,差分约束)