跳到正文

个人记录

差分约束!

lly_k_lyl_lyz约 1 分钟
原文
文章信息与版本

文章信息

收录
2026年3月22日
更新
2026年7月24日
篇幅
约 1 分钟

版本

  1. v1当前

Hello!

//2025//1/18

差分约束 例:

x1−x2≥3x_1 - x_2 \ge 3 根据不等式的性质,两边各自乘−1-1,改符号。

x2−x1≤−3x_2 - x_1 \le -3

(有点非常像最短(长)路)

这里用到了SPFA算法,so经常需要判断负环。

依然要用我们的老朋友vector和queue。

核心代码 如: void SPFA() {

C++
memset(dis,0x3f,sizeof(dis));
clock_t start=clock();
queue<long long> q;
q.push(0);
is_q[0]=1;
dis[0]=0;
while(!q.empty()) {
	int p=q.front();
	q.pop();
	is_q[p]=0;
	for(int i=0; i<e[p].size(); i++) {
		if(dis[e[p][i].v]>dis[p]+e[p][i].c) {
			dis[e[p][i].v]=dis[p]+e[p][i].c;
			if(!is_q[e[p][i].v]) {
				q.push(e[p][i].v);
				is_q[e[p][i].v]=1;
				cnt[e[p][i].v]++;
				if(cnt[e[p][i].v]>=n) {
					cout<<"NO";
					qwe=1;
					return;
				}
			}
		}
	}
}

}

原文